A script to allow the Raspberry Pi to connect to a know wifi router or automatically generate a Non Internet  Access Point if no network is found. You can then use SSH or VNC on the move and switch between the hotspot and home network without a reboot.

This is suitable for the Pi Zero W & Pi Zero 2 which have no LAN port or anybody who does not need an internet routed access point on a Raspberry Pi 3, 3B+ or 4. Just for direct Wifi access to the PI when you are out and about.

Works with Raspbian & PiOS - Bullseye, Buster, Stretch and Jessie.

Not compatible with PiOS Bookworm. Bookworm version here.

When i am home I like to have my Raspberry Pi connected to the home network and the internet but when I am out I would like to connect to it using ssh via an access point using a tablet, phone or laptop.

I wanted a Raspberry Pi that connects to my home networks Wifi when I am at home or generates a wifi Access Point when I am out.

I have done this in a previous script but, this is an updated process and more robust than my original script. So this article is how to setup a Raspberry Pi so it can automatically switch between a network wifi connection and a non internet access point.

 

If you do require an eth0 network/internet routed access point as you have a RPi4, RPi3 B+, RPi3 or a RPi 1/2 with a wifi dongle then use my alternative script at Raspberry Pi - Auto WiFI Hotspot Switch Internet

If you would just like a permanent access point then you can use this guide Raspberry Pi - Hotspot/Access Point dhcpcd method

Easy Installer Script: the setup in this guide is available in an installer at Raspberry Pi AutoHotspot and Static Hotspot Installer Script

Aim:

  • When your home:   On starting the Raspberry Pi it connects to your home routers wifi
  • When your out: On starting, if any known wifi connection is not found it will generate a hotspot so a direct wifi connection can be made to the Raspberry Pi by a tablet, phone or laptop.  Useful for SSH, VNC and webservers.
  • While in access point mode for RPi 1/2/3/4:  if an ethernet cable is connected the Raspberry Pi, then it will NOT have network/internet access

Additional Features:

Using a Cron, a timer can be setup so the wifi connection can be regulary checked. It will switch between a wifi router and amn access point without a reboot depending on the results. This is useful for

  • Raspberry Pi in car entertainment systems
  • Raspberry Pi Dash Cams
  • If the RPi looses wifi connection in your garden or near your home when using the camera or sensors.
  • You run a script or program at home connected to your router and wish to monitor it while you are out. As a hotspot is generated without a reboot the script/program is not interuppted.

It is also possible to run the script from a GPIO button so you can manually run the script to switch depending on where you are.

 

 Requirements:

This has been tested on Raspbian & PiOS - Bullseye, Buster, Stretch, Jessie. To see which version you have enter the command lsb_release -a

  • Raspberry Pi Zero W or Raspberry Pi 3, RPi3B+, RPi4
  • Raspberry Pi 1,2 or Zero with a Wifi Dongle*,
  • Wifi already configured for your home router

*some WiFi dongles don't work in adhoc/AP mode or don't work with with the nl80211 driver used with the RPi 3 & Pi zero W inbuilt wifi, so you may want to check this first before starting.

 This setup has been tested on Raspbian Jessie, Raspbian Stretch and Raspbian Buster using a RPi4, RPI3 B+, RPI3, RPI Zero W and a RPI 2 . A connection has been made to the Hotspot using an Android Tablet, Ipad2, Raspberry PI and Windows 10. All worked fine with SSH.

Note about Stretch, Buster & Bullseye Network Device Names

From Raspbian Stretch there has been changes to how the network drivers are named, called Predictable Network Interface Names,  and may be different for the usual wlan0 and wlan1 for wifi and eth0 for ethernet connections. Though the official Foundation version of PiOS seems to be keeping to the old standard names, at least at the time of writing,  this may not always be the case. For this guide I will use wlan0 as the device that is used.  

To check the device name for your setup enter the commmand iw dev and take a note of the "Interface" name. For wifi it should start with wl , replace your device name with any reference to wlan0 in the article, scripts and config files.

Step 1:

To start with hostapd hotspot client and dnsmasq lightweight dns server need to be installed.

Open a Terminal session.

Update Raspbian with the latest updates by entering the commands:

sudo apt-get update
sudo apt-get upgrade

 To install hostapd enter the command:

sudo apt-get install hostapd

enter Y when prompted.

To install dnsmasq enter the command:

sudo apt-get install dnsmasq

enter Y when prompted

The installers will have set up the programme so they run when the pi is started. For this setup they only need to be started if the home router is not found. So automatic startup needs to be disabled and by default hostapd is masked so needs to be unmasked. This is done with the following commands:

sudo systemctl unmask hostapd

sudo systemctl disable hostapd
sudo systemctl disable dnsmasq

Now the hostspot configuration file can be setup. This contains the name of the WiFi signal you will need to connect to (SSID) and the security password.

To edit the configuration files I will be using the nano text editor but if you prefer an editor with an point and click interface then replace nano with leafpad in the following instructions.

Hostapd Configuration

Using a text editor edit the hostapd configuration file. This file won't exist at this stage so will be blank.

sudo nano /etc/hostapd/hostapd.conf

download file here:



#2.4GHz setup wifi 80211 b,g,n
interface=wlan0
driver=nl80211
ssid=RPiHotspot
hw_mode=g
channel=8
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=1234567890
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP TKIP
rsn_pairwise=CCMP

#80211n - Change GB to your WiFi country code
country_code=GB
ieee80211n=1
ieee80211d=1

  • The interface will be wlan0
  • The driver nl80211 works with the Raspberry Pi 3 & Zero W onboard WiFi but you will need to check that your wifi dongle is compatable and can use Access Point mode.

For more information on wifi dongles see elinux.org/RPi_USB_Wi-Fi_Adapters

  • The SSID is the name of the WiFi signal broadcast from the RPi, which you will connect to with your Tablet or phones WiFi settings.
  • Channel can be set between 1 and 13. If you are having trouble connection because of to many wifi signals in your area are using channel 6 then try another channel.
  • Wpa_passphrase is the password you will need to enter when you first connect a device to your Raspberry Pi's access point. This should be at least 8 characters and a bit more difficult to guess than my example.
  • The country_code should be set to your country to comply with local RF laws. You may experience connection issues if this is not correct. Your country_code can be found in /etc/wpa_supplicant/wpa_supplicant.conf or in Raspberry Pi Configuration - Localisation settings

To save the config file press ctrl & o and to exit nano press Ctrl & x

(Note:  this bit for /etc/default/hostapd does not need to be changed for PiOS Buster or Bullseye. This is for the older OS's Stretch and Jessie)

Now the defaults file needs to be updated to point to where the config file is stored.
In terminal enter the command
sudo nano /etc/default/hostapd

Change:
#DAEMON_CONF=""
to
DAEMON_CONF="/etc/hostapd/hostapd.conf"

Check the DAEMON_OPTS="" is preceded by a #, so is #DAEMON_OPTS=""

And save.

DNSmasq configuration

Next dnsmasq needs to be configured to allow the Rpi to act as a router and issue ip addresses. Open the dnsmasq.conf file with

sudo nano /etc/dnsmasq.conf

Go to the bottom of the file and add the following lines (download here)


#AutoHotspot Config
#stop DNSmasq from using resolv.conf
no-resolv
#Interface to use
interface=wlan0
bind-interfaces
dhcp-range=10.0.0.50,10.0.0.150,12h

and the save (ctl & o) and exit (ctrl & x)

Step 2:

Now that hostapd and dnsmasq are configured we now need to make some changes to the interfaces file, add a service file and then add the autohotspot script.

The interfaces file is not required and should be empty of any network config. Depending which version of Raspbian you have this file may still contain network config.

Enter

sudo nano /etc/network/interfaces

If you file shows more than the standard top 5 lines like this

 # interfaces(5) file used by ifup(8) and ifdown(8) 
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

then make a copy of of your file and then remove any excess lines from the interfaces file.

To make a backup of your interfaces file use the command

sudo cp /etc/network/interfaces /etc/network/interfaces-backup

 DHCPCD

dhcpcd is the software that manages the network setup. The next step is to stop dhcpcd from starting the wifi network so the autohotspot script in the next step takes control of that. Ethernet will still be managed by dhcpcd.

Open dhcpcd.conf with the command

sudo nano /etc/dhcpcd.conf

at the bottom of the file enter the line

nohook wpa_supplicant

now save (ctrl & o) and exit (ctrl & x)

autohotspot service file

Next we have to create a service which will run the autohotspot script when the Raspberry Pi starts up.

create a new file with the command

sudo nano /etc/systemd/system/autohotspot.service

Then enter the following text or download here


[Unit]
Description=Automatically generates an internet Hotspot when a valid ssid is not in range
After=multi-user.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/autohotspot
[Install]
WantedBy=multi-user.target

and save (ctrl & o) and exit (ctrl & x)

 

For the service to work it has to be enabled. To do this enter the command

sudo systemctl enable autohotspot.service

 

AutoHotspot Script

This is the main script that will manage your wifi connections between a wifi router and an Hotspot.

It will search for any wifi connection that is setup on you Raspberry Pi by using the details found in /etc/wpa_supplicant/wpa_supplicant.conf

If no wifi signal is found for a known SSID then the script will shutdown the wifi network setup and create a Hotspot. Allowing you to connect to the Raspberry Pi from a wifi device using SSH or VNC.

 The script works with SSID's that contain spaces and by entering your routers MAC address it can be used with hidden SSID's.

Hidden SSIDs

If your routers SSID is not broadcast/hidden then find this section in the script

#Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie
#( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' )
mac=()

and enter your routers MAC address in the brackets of mac=() as shown in the example. Make sure mutiple MAC addresses are seperated by a space.

 

 Creating the autohotspot script:

Create a new file with the command

sudo nano /usr/bin/autohotspot

and add the autohotspot script. This can be downloaded from here


#!/bin/bash
#version 0.962-N/HS

#You may share this script on the condition all references to RaspberryConnect.com 
#must be included in copies or derivatives of this script.  

#A script to switch between a wifi network and a non internet routed Hotspot
#Works at startup or with a seperate timer or manually without a reboot
#Other setup required find out more at
#http://www.raspberryconnect.com

wifidev="wlan0" #device name to use. Default is wlan0.
#use the command: iw dev ,to see wifi interface name 

IFSdef=$IFS
cnt=0
#These four lines capture the wifi networks the RPi is setup to use
wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' | sed 's/\r//g'| awk 'BEGIN{ORS=","} {print}' | sed 's/\"/''/g' | sed 's/,$//')
IFS=","
ssids=($wpassid)
IFS=$IFSdef #reset back to defaults


#Note:If you only want to check for certain SSIDs
#Remove the # in in front of ssids=('mySSID1'.... below and put a # infront of all four lines above
# separated by a space, eg ('mySSID1' 'mySSID2')
#ssids=('mySSID1' 'mySSID2' 'mySSID3')

#Enter the Routers Mac Addresses for hidden SSIDs, seperated by spaces ie 
#( '11:22:33:44:55:66' 'aa:bb:cc:dd:ee:ff' ) 
mac=()

ssidsmac=("${ssids[@]}" "${mac[@]}") #combines ssid and MAC for checking

createAdHocNetwork()
{
    echo "Autohotspot by RaspberryConnect.com"
    echo "Creating Hotspot"
    ip link set dev "$wifidev" down
    ip a add 10.0.0.5/24 brd + dev "$wifidev"
    ip link set dev "$wifidev" up
    dhcpcd -k "$wifidev" >/dev/null 2>&1
    systemctl start dnsmasq
    systemctl start hostapd
}

KillHotspot()
{
    echo "Autohotspot by RaspberryConnect.com"
    echo "Shutting Down Hotspot"
    ip link set dev "$wifidev" down
    systemctl stop hostapd
    systemctl stop dnsmasq
    ip addr flush dev "$wifidev"
    ip link set dev "$wifidev" up
    dhcpcd  -n "$wifidev" >/dev/null 2>&1
}

ChkWifiUp()
{
	echo "Checking WiFi connection ok"
        sleep 20 #give time for connection to be completed to router
	if ! wpa_cli -i "$wifidev" status | grep 'ip_address' >/dev/null 2>&1
        then #Failed to connect to wifi (check your wifi settings, password etc)
	       echo 'Wifi failed to connect, falling back to Hotspot.'
               wpa_cli terminate "$wifidev" >/dev/null 2>&1
	       createAdHocNetwork
	fi
}


chksys()
{
    #After some system updates hostapd gets masked using Raspbian Buster, and above. This checks and fixes  
    #the issue and also checks dnsmasq is ok so the hotspot can be generated.
    #Check Hostapd is unmasked and disabled
    if systemctl -all list-unit-files hostapd.service | grep "hostapd.service masked" >/dev/null 2>&1 ;then
	systemctl unmask hostapd.service >/dev/null 2>&1
    fi
    if systemctl -all list-unit-files hostapd.service | grep "hostapd.service enabled" >/dev/null 2>&1 ;then
	systemctl disable hostapd.service >/dev/null 2>&1
	systemctl stop hostapd >/dev/null 2>&1
    fi
    #Check dnsmasq is disabled
    if systemctl -all list-unit-files dnsmasq.service | grep "dnsmasq.service masked" >/dev/null 2>&1 ;then
	systemctl unmask dnsmasq >/dev/null 2>&1
    fi
    if systemctl -all list-unit-files dnsmasq.service | grep "dnsmasq.service enabled" >/dev/null 2>&1 ;then
	systemctl disable dnsmasq >/dev/null 2>&1
	systemctl stop dnsmasq >/dev/null 2>&1
    fi
}


FindSSID()
{
#Check to see what SSID's and MAC addresses are in range
ssidChk=('NoSSid')
i=0; j=0
until [ $i -eq 1 ] #wait for wifi if busy, usb wifi is slower.
do
        ssidreply=$((iw dev "$wifidev" scan ap-force | egrep "^BSS|SSID:") 2>&1) >/dev/null 2>&1 
        #echo "SSid's in range: " $ssidreply
	printf '%s\n' "${ssidreply[@]}"
        echo "Device Available Check try " $j
        if (($j >= 10)); then #if busy 10 times goto hotspot
                 echo "Device busy or unavailable 10 times, going to Hotspot"
                 ssidreply=""
                 i=1
	elif echo "$ssidreply" | grep "No such device (-19)" >/dev/null 2>&1; then
                echo "No Device Reported, try " $j
		NoDevice
        elif echo "$ssidreply" | grep "Network is down (-100)" >/dev/null 2>&1 ; then
                echo "Network Not available, trying again" $j
                j=$((j + 1))
                sleep 2
	elif echo "$ssidreply" | grep "Read-only file system (-30)" >/dev/null 2>&1 ; then
		echo "Temporary Read only file system, trying again"
		j=$((j + 1))
		sleep 2
	elif echo "$ssidreply" | grep "Invalid exchange (-52)" >/dev/null 2>&1 ; then
		echo "Temporary unavailable, trying again"
		j=$((j + 1))
		sleep 2
	elif echo "$ssidreply" | grep -v "resource busy (-16)"  >/dev/null 2>&1 ; then
               echo "Device Available, checking SSid Results"
		i=1
	else #see if device not busy in 2 seconds
                echo "Device unavailable checking again, try " $j
		j=$((j + 1))
		sleep 2
	fi
done

for ssid in "${ssidsmac[@]}"
do
     if (echo "$ssidreply" | grep -F -- "$ssid") >/dev/null 2>&1
     then
	      #Valid SSid found, passing to script
              echo "Valid SSID Detected, assesing Wifi status"
              ssidChk=$ssid
              return 0
      else
	      #No Network found, NoSSid issued"
              echo "No SSid found, assessing WiFi status"
              ssidChk='NoSSid'
     fi
done
}

NoDevice()
{
	#if no wifi device,ie usb wifi removed, activate wifi so when it is
	#reconnected wifi to a router will be available
	echo "No wifi device connected"
	wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
	exit 1
}

chksys
FindSSID

#Create Hotspot or connect to valid wifi networks
if [ "$ssidChk" != "NoSSid" ] 
then
       if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
       then #hotspot running and ssid in range
              KillHotspot
              echo "Hotspot Deactivated, Bringing Wifi Up"
              wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
              ChkWifiUp
       elif { wpa_cli -i "$wifidev" status | grep 'ip_address'; } >/dev/null 2>&1
       then #Already connected
              echo "Wifi already connected to a network"
       else #ssid exists and no hotspot running connect to wifi network
              echo "Connecting to the WiFi Network"
              wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf >/dev/null 2>&1
              ChkWifiUp
       fi
else #ssid or MAC address not in range
       if systemctl status hostapd | grep "(running)" >/dev/null 2>&1
       then
              echo "Hostspot already active"
       elif { wpa_cli status | grep "$wifidev"; } >/dev/null 2>&1
       then
              echo "Cleaning wifi files and Activating Hotspot"
              wpa_cli terminate >/dev/null 2>&1
              ip addr flush "$wifidev"
              ip link set dev "$wifidev" down
              rm -r /var/run/wpa_supplicant >/dev/null 2>&1
              createAdHocNetwork
       else #"No SSID, activating Hotspot"
              createAdHocNetwork
       fi
fi

and save (ctl & o) and exit (ctl & x)

For the autohotspot script to work it needs to be executable. This is done with the command

sudo chmod +x /usr/bin/autohotspot

Thats it, you are ready to go. Now test that everything is working ok.

Thanks to Willem Me and Tino for there contributions to the development of this script.

Testing the Hotspot

To test that the RPi is setup ok reboot the RPI. When the desktop returns you should have the wifi icon Raspbian Pixel WiFI icon by the clock.
For those setting this up on a headerless RPi then you should see the pi on your routers network. 

To test the access point works ok edit the ssid name of your router in the wpa_supplicant file.

enter

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

and add 'off' to the end of your routers ssid. For example:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={ ssid="mySSID1" psk="myPassword" key_mgmt=WPA-PSK }

change to

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={ ssid="mySSID1off" psk="myPassword" key_mgmt=WPA-PSK }

save (ctrl & o) and close (ctrl & x) the file

Now reboot the Raspberry Pi.

Once the RPi is up and running the wifi icon near the clock should now be two red crosses Raspbian Pixel AP mode icon This means it is an access point, it could also mean your network is down but other devices should detect the access point. On a Tablet, phone or Laptop scan for wifi signals. You should see one for RPiHotSpot.

Select this as the wifi signal to connect to. The password is what you setup in the hostapd.conf file. From my example it is 1234567890

Wifi Connections-android

If you find this guide useful and wish to show your appreciation then you are welcome to make a donation or share a link to this article. There is no obligation to do so, this guide is free for use and support is available to everybody as long as I know the answer :)

I am the single developer of this script and website. Any support towards the costs are welcome.

RaspberryConnect.com

 

 

Local wifi signals in range on Android. Will be RPiHotSpot not RPI3Hot

For SSH and VNC the connection ip is 10.0.0.5 also if you have setup the Rpi as a webserver use the same ip to see the webpage.

For ssh use ssh pi@10.0.0.5

For vnc use 10.0.0.5::5900

 Once you are happy the setup is working ok change the wpa_supplicant.conf file back to your routers ssid. From the next reboot the autohotspot script will manage your wifi connection.

 

Setting up a Timer

If the autohotspot script is set to be run at set intervals, when you go out of range of your home router it will automatically generate a hotspot and then when you get back in range it will deactivate the access point and connect to the routers wifi. If you run a program in the background or use programs like tmux then any software you are running will keep working.

If you have an active ssh or vnc session running when the switch happens it will be lost.

Using a Cron job, tasks can be set off automatically at certain times, dates or intervals. For my use running the script every 5 minutes is fine but this can be changed to your needs. To setup a cron task enter the command

crontab -e

At the bottom of the file enter the command

*/5 * * * * sudo /usr/bin/autohotspot >/dev/null 2>&1

There is a space after each entry and * except the first *.

The first * position is for minutes. If you want it to check every minute just use * instead of */5

If you want to use hours, say every 2 hours enter it as

* */2 * * * sudo /usr/bin/autohotspot >/dev/null 2>&1

 Save the cron tab with ctrl & o and close it with ctrl & x

The cron job will automatically start straight away.

Disable Cron Timer

If you no longer need the timer running edit the cron with

crontab -e

and put a # infront so it is now

#*/5 * * * * sudo /usr/bin/autohotspot

The script will now only work at boot up or if you manually run the autohotspot script with the command

sudo /usr/bin/autohotspot

Note on Permissions:

by default the pi user does not need to enter a password to use the sudo command. If you are not using the default pi user and while doing this guide you have had to enter a password every time sudo is needed then you will find the the cron job will not work as it wont have permission to run the autohotspot script.

To fix this you can give the user permission to run the script without a password.
Enter the command

sudo visudo

enter your password
at the bottom of the file add the following line, where username is the user that will be using the script:

username ALL= NOPASSWD: /usr/bin/autohotspot

Now you will be able to run the script with sudo with the cron.

Thanks to Jim for pointing this out as an issue for some users.

 

If you are not using the default PI user and you are still have issues then check your default Paths from CRON for your user. It will need /sbin/ for iw.

Adding the path line to the cron will tell it were to look, PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Thanks to Atanas Atanasov for highligting this for non PI users

 


 

Script Removal

If you don't wish to continue using the autohotspot script then the Raspberry Pi can be revered back to a standard wifi setup with the following steps.

Disable the script with the command

sudo systemctl disable autohotspot

 

In the /etc/dhcpcd.conf file remove the line that was added

nohook wpa_supplicant

 

If you had previous config in your interfaces file and made a backup you can restore your original interfaces file with the command

sudo mv /etc/network/interfaces-backup /etc/network/interfaces

Then reboot.

The autohotspot script will no longer have control of your wifi. Dnsmasq and hostapd can be uninstalled if you no longer need them.

 Trouble Shooting

  • If you get no wifi connection or no hotspot  then it is most likely the autohotspot script is not executable or the service has not been enabled

redo the follow commands

sudo chmod +x /usr/bin/autohotspot

 

sudo systemctl enable autohotspot.service

 

  • You are in range of your router but it only creates a hotspot. If there is an issue with connecting to the router, such as the password is wrong. The script will fall back to the hotspot so you still have some type of connection. Check your password in the wpa_supplicant.conf file. 
  • You can connect to the hotspot via an Android Phone but you can't get a ssh connection. Some users have found this issue where Android uses there data connection rather than the wifi. Disabeling data has allowed them to use ssh.   
  • If this setup is not working as expected you can check the script for errors by running it manually in a terminal window with the command, sudo /usr/bin/autohotspot ,you can also check the service status with, sudo systemctl status -l autohotspot ,and if the hotspot has failed try, sudo systemctl status -l hostapd
  • You need to add a new wifi network to the RPi but it is in Hotspot mode so you are unable to scan for new wifi signals. You will need to add the new network to /etc/wpa_supplicant/wpa_supplicant manually. Enter the following details replacing mySSID and myPassword with the correct details. If your router has a hidden SSID/not Broadcast then include the line;  scan_ssid=1
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={ ssid="mySSID1" psk="myPassword" key_mgmt=WPA-PSK }
  • Unable to Authenticate the RPIHotSpot connection from another device. Make sure the password for the wifi connection is the one in the hosapd.conf file and not your Raspberry Pi's user password. The default pasword is 1234567890

Change Log: here

 


Add comment

Comments  
Change wifi credentials via web page.
Hi,

Keep up the great job! I would like to create a webpage where you can enter new WiFi credentials if a connection cannot be made. This webpage would initiate a hotspot when no connection is available. I could then connect to the hotspot and browse to the webpage running on the Pi. On this webpage, I could input new credentials, which would be stored on the Pi. After rebooting, it would connect to the newly available WiFi network. If it cannot connect, it would start the hotspot again, and so on. I presume this could work with a timer cron, but is it possible to do this without manually modifying the wpa_supplicant?

Cheers,

Steve
Change wifi credentials via web page
Hi Steve

I have another script for the latest PiOS Bookworm called AccessPopup as they have changed the way the wifi works. I am currently working on an update that will add several new features including a webpage for settings, so that may interest you when it is done. I currently have no plans to update this script on this page for now.

For the Autohotspot script for the older OS's. I would trigger the webpage when the hotspot is created during the function createAdHocNetwork() and close it when the function KillHotspot() is used.
Once the new credentials have been updated you can restart the autohotspot.service which will run the script again and connect to the new Wifi network without the need for a reboot.
If you add sudo /usr/bin/autohotspot to a cron timer then it will check the wifi status every few minutes and swap back and forth as required.

You will need to edit the wpa_supplicant.conf file to update the details though. It is possible to create a separate wpa_supplicant.conf file and use it when when wpa_supplicant is started in the script;
wpa_supplicant -B -i "$wifidev" -c /etc/wpa_supplicant/wpa_supplicant.conf
Just replace the path to the .conf file, but this will not be updated when the user edits the password with the wifi GUI or Raspberry Pi Configuration so probably better to use the existing config file.

The automated installer for this script (link at the top of the page) also has options to add a new network to the Pi or edit an existing password but it will need to be accessed via SSH or VNC.
Dietpi
Hi, thank you for your reply. Is it also compatible with dietpi?
DietPi
Hi Steve I believe it is, from other users. I have not tried it myself. As long as dhcpcd is used for the network there is a good chance it will work.
AccessPopup
Hi, I am very interested in your AccessPopup script. When do you think I can test it ;-)
AccessPopup
Hi Steve The basic version is available on the website. The link is at the bottom of the home page. The more featured version is currently in development and will be available later this year. I have no date yet as it will be worked on when time allows but any updates will be put on the website. Hopefully it won't take too long.
I want to run flask
Hi, I want to run the Flask web API when it is in hotspot mode. and when it is connected with local network I should be able to access pi over SSH.. I am working with Dietpi OS and referred this tutorial [Raspberry Pi Zero 2 W Webserver using Flask Library with DietPi OS] https://microdigisoft.com/raspberry-pi-zero-2-w-webserver-using-flask-library-with-dietpi-os/ . and able make and access web page on when my PC and PI both connected on same network.

Let me know how I can achieve that I will able access web page generated by Fask WEB API page on hotspot mode when Pi is not connected with local network
I want to run flask
Hi

To view the Flask web page being served on port 5000, while the the Pi is running the access point;
connect to the Access Points wifi and then in the web browser enter http://10.0.0.5:5000

For the setup on this page, to use the Pi while it is an access point you can use 10.0.0.5 then the port number for the Flask server. If the page you wanted is in a sub page then you would use http://10.0.0.5:5000/mysubpage.htm

to use ssh it is ssh pi@10.0.0.5 and for VNC it is server 10.0.0.5::5900

If you are using one of the other scripts on this site, then take note of the Access Point IP address as they are all different.

I have not used this script with Diet Pi, but I presume it is working o for you.
Flask
Perfect! I have implemented Flask API successfully to run the Webserver Page when my RasPi is in hotspot mode and also simultaneously I can Access the pi over SSH. Thanks for your great script.
Flask
Thanks for the update, that's good to hear. Glad you have it working and confirming it works on Diet Pi.
temp ap
is it possible to make the rpi work as an access point when rebooted alowing connection with in say 2mins or untill logout , after this goes back to connecting to the set network ( this would be to allow local updates etc if the set wifi goes off for any reason and i have no acces to the pi as is up high or something )
temp ap
Hi Oly
It's not possible to limit when it the AP is generated, but you can setup a Cron Timer. This checks the wifi status and whenever the Network goes down the AP automatically pops up. Then reconnects to the Network when it is back. The lower part of the article has a section on setting up a timer with the Cron.

I have done a new script for PiOS Bookworm which will check the wifi status every 2 minutes and switch back and forth as required as it's standard function. This won't work on Bullseye/Buster.

Hopefully these options will be of use to you.
Trouble with hostapd
Hi, I folowed your guide and used the easy installation script, but I'm havin the following issue:
When I turn off the SSID on my router to enable the hotspot, It fails with an error that, after searching, is that hostapd can't start due to an error. The error is that it can't read /etc/hostapd/hostapd.conf, tough I have made sure it is where it should be.

If I run sudo hostapd /etc/hostapd/hostapd.conf from the command line it activates the hotspot fine.

I'm grateful for any help.
Trouble with hostapd
Hi Rubi The issue may be around the /etc/default/hostapd file if this was edited during the manual guide. Check that the the line DAEMON_CONF= has no path to the hostapd.conf file and starts with a # #DAEMON_CONF="" This is not required for the last two OS's but will cause the error you describe if used. Its this section on the manual guide: Now the defaults file needs to be updated to point to where the config file is stored. In terminal enter the command sudo nano /etc/default/hostapd Change: #DAEMON_CONF="" to DAEMON_CONF="/etc/hostapd/hostapd.conf" Check the DAEMON_OPTS="" is preceded by a #, so is #DAEMON_OPTS="" And save. The installer will check which version you have and ignore the file for later OS's but if it is already edited it may still be wrong. Let me know if this doesn't fix the issue. You can also delete the /etc/default/hostapd file if it still causes isues.
RE: Trouble with hostapd
Thanks roboberry! That did it! It works perfect.
Trouble with hostapd
No problem, That's good news. Enjoy
Thanks!
Just wanted to say, thanks so much for these instructions/code, it's a total time/lifesaver! I used this a few years ago for a small project, and I thought I was going to completely change it this time around, however, turns out you can't get an esp32 to do espnow, and be an ad-hoc webserver at the same time (annoyingly it can do espnow and be a client connecting to a wireless router.. I figure someone just hasn't done the code for what i need yet) Anyways, back to using lora between my arduino and raspberry pi, and this code helps me set up my pi at home, but be a super solid webserver in the field. Cheers :)
Thanks
Hi David, you are welcome. I'm glad to hear you find it useful. Sound like you are having a similar issue to what caused me to create the script several years ago. I had an Android tablet and google decided to drop the Hotspot feature in an update. I was using it for my Pi's to connect to. So i needed to get the Pi's to have the Hotspot and not the tablet but I didn't want it to be permanent. So I put the script together and it has turned out quite a lot of other people also find it useful. Hopefully someone gets the esp32 working how you need it but until then at least you have a solution. Thank you very much for the donation, much appreciated.
Script seems to be disabling Wifi
Have a new Rpi 4b 8gb running Bullseye. Have tried 3 times now but end up with the same result. Am setting up via wired LAN cable and accessing via Vnc.

- sd card flashed with the latest version of HamPi 2.0
- Rpi boots and everything looks hunky dory
- enable Wlan, WiFi symbol appears next to clock and succesfully connect to my home Wifi
- Follow the process/instructions
- on reboot the Wifi symbol disappears from the desktop and is replaced by up and down arrows. When I click there it tells me 'No wireless LAN interfaces found'

Help :-)
Script seems to be disabling Wifi
Hi Paul

I have not used HamPi so I don't know it's setup. It will need to be using dhcpcd for wifi and lan management rather than network manager or dhcp etc.

if the the dhcpcd service is running and HamPi is based on PIOS then it "should" work ok.
check dhcpcd is running with sudo systemctl status dhcpcd
If you don't see "Active: active (running)" then it is not compatable with this setup.

Presuming it is compatible then what you describe is correct. The wifi Icon and double arrows are from dhcpcd but when the access point is created wlan0 is disabled in dhcpcd, which explaons your message. It is then managed by dnsmasq and the AP by hostapd.

While the Pi is an access point, check if you are getting an ip for wlan0 using the command; ip a
this should show wlan0 ip address as 10.0.0.5 (for the guide on this page) and other wifi devices will see the Wifi network of RPiHotspot being broadcast.

If you do have dhcpcd running and still have an issue let me know but HamPi will need to be setup like PIOS for this to work as written.
SSID might be seen but without data connection
I did something like this but we had the issue when using wifi routers with SIM card and those did not have actual internet connection so showed an info screen or setup screen instead. We had to make a check for actual internet connectivity, like accessing a file on a known server and check the content.
Otherwise it would get stuck with no internet access via wifi and no hotspot.
It was also crucial to check it while going through all ssid's in the wpa_supplicant file, checking for ACTUAL connection content and otherwise move on to the next SSID.
SSID might be seen but without data connection
Hi Henrik

Thanks for the feedback. It's nothing I have needed to try so not come across that yet, I will keep that in mind for the next version. Thanks
Turn on AP when wifi disconnects
Fantastic project!
I want to make my ZeroW turn on the AP as soon as a wifi connection disconnects. I read something about running a script in a wpa_cli action-script, but I'm a little confused about which script to run etc.
Has anyone implemented that?
Turn on AP when wifi disconnects
Hi Flo

Thank you, You can get the script to run every minute with a cron task. The wpa_cli stuff is already taken care of in the autohotspot script.
There is a section towards the bottom of the guide about setting up a timer.
If you follow that you it will be setup as you need.
Then the /usr/bin/autohotspot script will be run every minute, for example, so if the signal is lost from your router an access point will be created within a minute. And then reconnect when it is back in range.

Just be aware that any ssh/vnc or other active connection will be lost when the switch happens.
The
Fantastic project and was just what I was looking for. Just a quick observation - it would not work for me (RPi 3B+ running BullsEye) until I changed line 43 in the autohotspot script to use address 10.0.0.5? It currently has 192.168.50.5 on the download file. Just in case anyone else has this issue.
The
Hi Ade

I'm glad you find the script useful.
I think the issue is a continuity error :)

It looks like you have followed the "No Network" guide, that uses ip 10.0.0.5 up to the dnsmasq.conf part and then followed the "with Internet" guide that uses ip 192.168.50.5.

You will need to change the /etc/systemd/system/autohotspot.service file so it points to
/usr/bin/autohotspot
Then add the autohotspot script from the "No Network" guide in to /usr/bin/

as I suspect they are both for autohotspotN
Auto-connect not working
Device: RPI Zero 2
For people that faced the same issue me: Hotspot working but auto-connect not working.
Solution:
- in https://www.raspberryconnect.com/images/Autohotspot/autohotspot-95-4/autohotspot.txt
- remove the quotes in echo command, line "if (echo "$ssidreply" | grep -F -- "$ssid") >/dev/null 2>&1" thus becoming
- "if (echo $ssidreply | grep -F -- $ssid) >/dev/null 2>&1"

I hope it will be useful. Enjoy!
Auto-connect not working
Hi Emanuel

Thanks for your feedback.
Could you give me a bit of detail on your issue please.
The quotes are used so that any spaces in a SSID name don't cause it to be read as two separate entries of SSID. If the SSID has no spaces or special characters then the quotes should make no difference.
Could you also give me an example of the format of your SSID please so I can look into this further please.
Auto-connect not working
For me if I use quotes the if condition always returnes False (empty string result), so it will never connect to the required SSID even if it is present in the list. Without quotes it works correctly, it returns the correct string "SSID MY_WIFI_SSID" and then triggeres the connect.
My SSID is composed only of capital letters. But in the list there are more, even with spaces.
Do you think that if my SSID would have spaces then I need the quotes again?
Auto-connect not working
Hi Emanual

If the ssid string has spaces and the quotes are not used then it will be broken into two strings.
If by chance you have the uppercase string SSID: in you ssid then that will be an issue as thats the keyword to find the local broadcasting SSID's in the scan. SSID: will be removed using the space as a break from the string before it is matched to wpa_supplicant.conf.

I think what may be happening without the quotes it is splitting both the wpa_supplicant entry and the ssid broadcast scan by the space which is giving a match but as matching partial strings. Working for you but not ideal. Similar SSIDs could cause a match but a connection won't be possible. It will then drop back to a Access Point.

I would keep the quotes. Spaces should be ok but SSID is most likely a problem.

Let me know if that doesn't help and I will set up a Pi to have a closer look using your ssid format.
Auto-connect not working
The SSID in the wifi name was just an example. My wifi name has only capital letters let's say "MYWIFI" which works without quotes in the "if" statement but doesn't work with quotes. Do you think there will be issues if my wifi name is "my wifi" (lowercase with space) or "MY WIFI" (uppercase with space)?
Auto-connect not working
Hi Emanuel

I thought that might be the case but it did make me think if SSID was used, it would probably cause the same issue.

I have set my router up so it literally was "MY SSID" , if the quotes are removed from the script then it will just go to the access point. As soon as the quotes are back in it works perfectly as expected.

I'm not sure why are you are seeing the opposite. Was your wpa_supplicant.conf file created in windows and dropped in the /boot partition of the SD card?

If it was it may be that there are some extra characters that are causing issues. The script does remove windows end of line characters but other special characters may cause an issue.

running dos2unix with /etc/wpa_supplicant/wpa_supplicant.conf may solve the issue if that is the case.
Though the Pi can handle a windows derived file for making the wifi connection. The autohotspot script is not so forgiving in the matching part of the process with some windows created files.

There will be no issue in using upper or lower case characters at all or using spaces with the quotes back in. Comma's and slashes will cause an issue.
Pi Zero W issues
Hello, I love this software and it was working in the past both on windows laptop and android with my pi zero w, but I am having some issues:

Laptop will connect to pi wifi network, but I cannot see my nodered ui webserver. After running ipconfig in cmd on windows, I see

Autoconfiguration IPv4 Address. . : 169.254.42.241
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . :

Using my galaxy s10+, It used to connect and forward me to the nodered webserver (http://10.0.0.5/ui/), but instead of connecting to the device, it rejects it immediately without any errors.. very frustrating.

Im not sure what has changed. I tried to Start fresh but there is something I am missing as I get the same results. Please help!
Pi Zero W issues
Hi TheOzarkWizard

There looks to be an issue with dnsmasq as your laptop is getting a 169.254 ip address. This is a fallback ip that is generated when dnsmasq has failed to create create 10.0.0.5 for some reason. As you are able to see the Pi's ssid then hostapd seems to be working ok.

On the pi when it's an access point, check sudo systemctl status dnsmasq. see what issue it reports.
There will usually be an issue with /etc/dnsmasq.conf.
check this line is correct
dhcp-range=10.0.0.50,10.0.0.150,12h


let me know what any errors are if this doesn't help.
Not hotspot detected
I double checked all the entries, and then tested with the "ssidoff" modifier. Now sadly I do not see a hotspot and cannot ssh via 10.0.0.5. So now I have no method of communication. This is with Raspian on a RPizeroW. I would REALLY like to get this to work as it would solve a big problem! Thx for the work that went into this.
Not hotspot detected
Hi Jack

Usually if there is no hotspot ssid then the hostapd.conf file has an error.
Hopefully you can use a screen with the Pizero to check the setup.
With your ssid still set to off run sudo /usr/bin/autohotspot and see what feedback it gives.

Then check sudo systemctl status hostapd
and see if it is running or any errors. Also do the same for dnsmasq. These may highlight config issues.
The country code in hostapd.conf is also important but that should be set.

Other things to look at:
If wpa_supplicant.conf was created on Windows and put in the Boot folder on a PC there may be some hidden characters causing an issue. Though the script can handle end of line characters some others may cause an issue.
Run wpa_supplicant.conf through dos2unix to remove any issues.
The Pi itself will be able to use wpa_supplicant.conf from Windows for normal wifi but the autohotspot script has limited compatibility.

You can just run sudo /usr/bin/autohotspot and modify the ssid in wpa_supplicant.conf to check if it works rather then rebooting. Rebooting will solve issues if a failure leaves it in a non complete state

Let me know if you have further issues. Also can you confirm if you are using PiOS Buster or PiOS Bullseye.
No hotspot detected
Indeed there was an error in the hostapd.conf file. So all is good.
Many thanks for your quick assistance and sharing this program. I will check on the 'Donate' button!
No hotspot detected
ah! they sneak in everywhere. Good to hear it's up and running. Thanks for the donation, very much appreciated.
Ben
I see the RPIHotspot on the list of available networks but I get the following error when I attempt to ssh from Ubuntu using ssh pi@10.0.0.5 -> permission denied, please try again. I added */5 * * * * sudo /usr/bin/autohotspot >/dev/null 2>&1 to crontab and added pi ALL= NOPASSWD: /usr/bin/autohotspot to visudo. Note.. I am using the default rpi username "pi" and SSID password. Any assistance would be greatly appreciated. Thanks!
Ben
Hi Ben

If you are able to get as far as attempting to login with ssh then the access point is working. You can confirm this if you can activate VNC and make a connection through that or just ping 10.0.0.5 from Ubuntu.

It looks like the issue is with ssh. It expects the user to have a password so I presume that is why you are getting Permission denied rather than Connection Refused.

To access a user that has no password you need PermitEmptyPasswords set to yes in /etc/ssh/sshd_config
https://man7.org/linux/man-pages/man5/sshd_config.5.html

Hopefully that will get it working. Let me know if you have an other issues with the access point.
had to add execute permission
I had to say: chmod +x /usr/bin/autohotspot
That's missing or not needed? seems to be working now that I did it
had to add execute permission
Hi Kevin

The instruction to add the permissions is in the guide. It's the last step before testing. Though it wasn't highlighted as a code line like the others in the guide. So I can understand it being missed. I have updated the guide so it stands out better. Thanks for that.
Does not detect local wifi at power on
When I power on the Pi Zero W with a fresh (and updated) OS install and your scrips, the Pi Zero goes into hotspot mode, even when my local WiFi network is running. If I login (using the hotspot or direct keyboard connection) to the Pi, issue sudo reboot, the Pi comes back connected to my local network. If I login using ssh over the network and issue another sudo reboot, the Pi comes back as a hotspot. It just ping-pongs between hotspot and connected to my Wifi network on each reboot. It alway starts as a hotspot when powered on. Is this normal behavior? I have checked all the scripts and they look correct. If this is not normal, then any suggestions on how to diagnose the problem would be appreciated. Thanks, and what a great set of scripts you have created!
Does not detect local wifi at power on
Hi Mark

It sounds like the script is setup ok but I think the issue is around the wifi signal.
When the Pi is running as standard it is constantly monitoring the wifi signal and as soon as it detects your router it will connect.
With the autohotspot script it will do a scan that only lasts a few seconds. So only the strongest signals get detected.
If your router is not in the initial scan then it will go to the hotspot.

You can monitor what SSIDs are detect if you connect the keyboard/screen and instead of rebooting run the command sudo /usr/bin/autohotspot or sudo autohotspot (the net enabled script is autohotspotN)
the script will rescan for your router and output what wifi signals it has found. It will then switch between hotspot and local wifi depending on the results.

The timer section of this guide may help you. You can set up a timer using the cron which will run the script every minute. So if it initially goes to hotspot it will probably switch back to your router after 1 minute. If your signal is being drowned out by other routers or interference in your area you may find the pi switched back and forth which is obviously not much use but maybe worth a try.

Changing your routers channel may help if nearby routers are using the same channel but as most routers try to use the best channel that may not help.

Let me know if you need further info and i'm glad you like the script, hopefully these suggestions help.
Solved
Thanks for the fast response!

I checked the output from the autohotspot script, and my local network was at the top of the list.

I then remembered when I first setup my Pi Zero W, I had my router assign the IP address, as I do with a lot of my peripherals, and not the Pi. Once I deleted that rule from my router, the autohotspot script started working as it should.

Not sure if this is a remote edge case you might want to consider for a future version.

Thanks again for your great work!

Mark
Solved
Hi Mark

Thanks for the update.
As your router was found in the list it should connect ok. When the script detects your SSID in the returned list, it basically puts the Pi in a the wifi state that it would be without the script installed. The Pi should connect as usual and accept the IP address from your router. The only real difference is that there is a check 20 seconds later to see if the Pi has received an IP address from the router. In case of some type of connection error. If it hasn't received an IP, it will go back to a hotspot.
20 seconds should be plenty of time to receive the IP as it should be 4 - 6 seconds.

When you run the sudo /usr/bin/autohotspot command and your SSID is in the detected list it will tell you it is connecting to the wifi network.
Then 20 seconds or so later it will either show the cursor if all is good or say that it is falling back to the hotspot.
If that's the case then there is an issue between the Pi and Router.

If the autohotspot script isn't installed then the Pi will just keep trying to connect to the router until it is successful.
Though if it fails to many time wpa_supplicant adds disabled=1 to the routers entry in /etc/wpa_supplicant/wpa_supplicant.conf so it is not used again, this is normal function in this situation.

Maybe that may help if you use your rules again but I will test this my end when I get to do the next set of updates.

And thank you very much for your generous donation, very much appreciated.
Can see AP - Can't get IP
Hi! I have been following this and I have got as far as rebooting and I can see the new AP's SSID. However when I try to connect via my phone (Android 11) it says "Couldn't get IP address" not sure what I have got wrong. I copied and pasted everything and the only bit I changed is the AP SSID and password. I have a caveate that I am using DietPi rather than full RaspberryPi OS, could that be the problem?
Can see AP - Can't get IP
Hi Kelvin

If you have an issue with the IP it is probably dnsmasq. Check for errors with sudo systemctl status dnsmasq
and see if you get any errors shown while the AP has been started.

I have not used it with DietPi. The PIOS uses dhcpcd as the network manager so if DietPi uses dhcp or other network manager then that will be the issue. The script disable dhcpcd for wlan0 when it is an AP but won't disable other network managers if they are running. If you don't then there can be two IP address for wlan0 which can cause connection errors.

If you are using dhcpcd then let me know if you get a dnsmasq error and I will look into it further.
Any
Hi - I've installed this via script on two RPiZero Ws. Each time I force the hotspot, I briefly connect with another device then the RPi shuts down. Has anyone seen this happen or have suggestion on why?
Any
Hi Ken

That seems a bit odd. There is not a function in the script or the setup to shutdown the Pi at any stage so I would suggest the error is elsewhere.
I have used these scripts with all types of Pi's for several years and not experienced this issue.

Maybe the system logs will have a clue. Other areas I would look at is power supply issues or file system errors.

All that changes is the WiFi chip is put into Access Point mode, but it's extremely unlikely you would have a physical error on both Pi Zeros.

By Force Hotspot I presume you mean renaming the ssid in wpa_supplicant.conf?
Where both Pizero's using different SD cards and Power supplies?
Multible networks?
Hi, first of all thanks for this great guide.
My question is, can i add multible networks in the wpa_supplicant.conf?
So the RPi checks if one of them is available or otherwise creates the hotspot?
Multible networks?
Hi Fendo

You are welcome.
Yes the script works with multiple networks in wpa_supplicant.conf.

It simply tests if any of the SSID's are in range in order of entry. If it finds 1 in range it will activate wpa_supplicant to work as it normal does.

If two networks are in range the Pi will connect to the strongest signal or the one set with the highest priority as it normally would without the script running.

If no SSID's are in range it will generate the access point or if a connection to a SSID in range fails to issue an IP address to the Pi.
Thank you first. I am new to the raspberry community and coding and very impressed of your work. The script itself and the bunch of suitable tutorials;
even more the fact that you share it for free.
If the whole world would work well like you;
structured, updating and with a plan;
I am convinced it would be a better place.
How long did it take to complete this ?
Did you enlist someone's assistance ?
Would you describe yourself as a professional software engineer or rather a hobby programmer ?
Only for giving me a better picture of everything ...
(It's something different to write the script than
just to make it run. This even runs by itself.
Autorun, lovin' it. Getting what I want without
the necessity of understanding anything.)
Peace in the internet and have a nice week.
Hi RRB-fanpost :)
Thank you for your kind words. I'm glad you have found it useful.

I wrote the first basic version in 2014 over a weekend for my own needs and thought it may be useful to others. So I made it available in the spirit of the linux community. It's grown a bit since then as I have developed it and with various requests from the Raspberry Pi community. It's 99% my own script with a few tweaks from those noted in the articles.

I'm just a hobby programmer, very much research and trial & error to get the original version working. It's been used in some diverse projects which is good to hear about.

Thank you and a Nice week to you.
Finally a recent guide for the AP setup and love the status checking.

One question - how can I use both the wifi client and AP at the same time?

Thanks!
Hi SiW80

For the Autohotspot it is not possible to have client wifi at the same time as the AP because it will mess with the switching setup. My other guide for a permanent hotspot can be used for both, which is also available in the installer.
So if you set up the static Hotspot and then make a slight alteration to /etc/dhcpcd.conf.
move nohooks wpa_supplicant below interface wlan0

nohook wpa_supplicant
interface wlan0
static ip_address=192.168.50.10/24
static routers=192.168.50.1

to


interface wlan0
nohook wpa_supplicant
static ip_address=192.168.50.10/24
static routers=192.168.50.1

Then when you connect a USB Wifi dongle as wlan1 it will connect to a router.
Device connected to the AP will not get internet from the Wlan1 WiFi but the Pi itself will.
You will need to change the IP tables from eth0 to wlan1 to set that up.
Thanks - this is for a Pi Zero W so what would I need use as there is no USB wifi or Ethernet used.
Hi SiW80,

To be able to create an AP and to connect to a separate WiFi network you will need to have two WiFi devices.
Wlan0 will be the Pi Created Access Point
Then by adding a USB Wifi adaptor as wlan1 it can also connect to a router as well.

On the Homepage, see the "Static Hotspot" article, at the bit about ip tables change any entry for eth0 to wlan1. plus the dhcpcd.conf changes i previously mentioned.

The autohotspot setup can only connect to one or the other at a time. There is an option to switch on demand which is useful for testing setups but not practical for normal use

let me know if you need more info.
Well, I too would agree that this is a fine tutorial, thank you! However, I can not get the to connect to my office router. I have looked over some of the good comments and have looked over various issues, like the MS end of line, eol. My office router is not broadcasting and I have added scan_id=1 to my spa_supplicant.conf and I have added the mac address to the autohotspot script. Any suggestion would be appreciated, thank you!
Hello Cy Drollinger

I have just checked out the hidden ssid using the mac=() section on my wifi extender. That worked ok.

What I suggest you do, presuming you can access a terminal window. With your works routers mac address setup in the /usr/bin/autohotspotN
run sudo /usr/bin/autohotspot

It will list wifi devices in your area, one of them will look something like SSID: \x00\x00 .....
This is the Hiden ssid. If the script detects it it will report:
Valid SSID Detected, assessing wifi status"
It will then attempt shutdown the hotspot.
If it works you will loose SSH or VNC connection if you are using them.
Otherwise it will say its going back to a hotspot.

If it goes back to hotspot the issue is with wpa_supplicant not liking the details in wpa_supplicant.conf and not the Autohotspot setup.

I would suggest disabling the autohotspot setup and getting the Pi to successfully connect to your works router. Then re-enable it and it will work.


To disable autohotspot:
sudo systemctl disable autohotspot
then in /etc/dhcpcd.conf change
nohook wpa_supplicant
to
#nohook wpa_supplicant
and reboot

to re-enable it them use
sudo systemctl enable autohotspot
and remove the # from nohokk .....

Let me know if this doesn't help.
Hi, many compliments ! I was looking for something like this, you saved me days of struggle...One question: I would like this script NOT to be automatic but “on demand”. When I push a button for 15 sec on my PI I want it to go in AP mode. Then I will present a webpage to connected user, he will compile a couple of fields (SSID & Password) and hit a “restart” button. From this moment on, I will copy these fields in my wpa_supplicant file and will restart in WiFi mode forever. This way I can make a first-time configuration of my device easily. Could you give me some hints on how to modify/organize your scripts ? Thank you again !
Is the current script possible to set this up to connect to a wifi hotspot and share the connection through a switch connected to Pi eth0? I'm new to this and might not be using the correct terminology. I believe it's called bridging? My topology: Cell Phone Hotspot Pi Wifi Pi eth0 Swithch multiple computers via eithernet.
Hi David

If the device is connected to the eth0 port then the Internet version of the script does this by default. The Direct script on this page is not setup for eth0 connections.
If you use the installer script, link at the top of this page or on the home page, you can change the setup to the Autohotspot Internet version.

The internet version will route the device connected to the WiFi hotspot through eth0.

If you only need eth0 then it will work.
Also check the device is listed as eth0. if not you can change it in the /usr/bin/autohotspotN script.
near the top are these lines:
wifidev="wlan0" #device name to use. Default is wlan0.
ethdev="eth0" #Ethernet port to use with IP tables

Just replace "eth0" with whatever the device is you are connection to.

The computers connected to the eth0 "switch" will be on a different network, The Pi and devices connected to the Pi's Hotspot will be able to connect to the computers on the Eth0 connected network but it is possible that a computer connected to eth0 doesn't connect to a device connected to the Pi's Hotspot. If that is the case then additional "Routing" needs to be setup but that will be unique to your setup.

My setup is:
Cell Phone -> Pi Hotspot -> (Pi Eth0) > Home Router > Multiple Computers on Home Router Network. This works both ways to all devices.
Works great, thanks!
Wow. This worked flawlessly on the first try.
I could never had pulled that trick by myself in a thousand years. I realize how little i know...
THANK YOU for setting this up and sharing with us mortals. I am forever in debt ;-)
Hi LoloJi
You are welcome, your comments are payment enough. I think you must be the immortal one if you have a thousand years to work on a projects. With enough hours and motivation you can achieve whatever you need :)
Now thats a nicely detailed tutorial. Im going headless and this is really helpful!
Hi ukdrilla

Thank for the feedback, i'm glad you find it useful.
Hello! I followed your directions, up to the point where it says, "To test that the RPi is setup ok reboot the RPI." I rebooted the RPi, and I got a rainbow splashscreen at the beginning of the bootup process and it just hangs there, nothing else happens. Ctl-Alt-Del does nothing. It's just stuck.

I'm running Rasberry Pi OS Buster on a RPi 4. I have it booting from an SSD plugged in to the USB instead of from a SD card (there's no SD card in the Pi at all). Any idea how to fix this?
I already looked up some things in google and then talk about having bad power supplies, but my power supply is the one made for the Pi 4 by the raspberry pi foundation, and I've been running the pi for weeks, rebooting, running from the SSD as a boot drive, and all has been working fine right up until I followed your tutorial.

I also plugged the SSD into an other computer and added `boot_delay=1` to the config.txt file, since this was mentioned as a fix for people having the pi hang on boot on the rainbow screen, but it didn't help anything.
I'm guessing I need to roll back some/all of the changes I made with your script, but which ones?

I can boot from an SD card instead and then access the SSD drive to modify files on it. I just don't know what to modify. (Booting works without any problem when I boot from the SD card instead (which has none of your tutorial's modifications on it--it's just plain vanilla Raspberry Pi OS Buster.))
Hi David

That's rather frustrating. To me that sounds like it's more to do with the firmware or intial preboot than anything else on the OS. There has recently been a bigger update to the OS and Firmware. Did you do an apt upgrade and then follow my guide at the same boot at all?

The autohotspot modifications don't take effect until the network is available, which is a later stage in the boot process so won't cause the issue you see. The only permanent change is the no hooks line in /etc/dhcpcd.conf which will just stop your wifi connecting to your router. The autohotspot script only starts at the final stages of the boot process, after te desktop is up, and will only make changes to the network only if the router is not found and that is essentially disabling wifi network and starting dnsmasq and hostapd.

If you was using a SD card and you just see the rainbow screen I would say the SD had a file system error but that's less likely on SSD.
Have you re enabled USB boot in raspi-config from a SD card boot?

If you would like to remove my script from your SSD then in /etc/dhcpcd.conf remove the line nohook wpa_supplicant

then in /etc/systemd/system/ delete autohotspot.service

Then next time you boot the SSD wifi will be available as soon as the network is up and the autohotspot script will not be run. The service will error and the boot process will continue. Hostapd and dnsmasq are disabled by default so will not be running.
This will remove any effect of my script and you can debug with the standard setup.

I would be interested in what the issue is when you resolve it. If you have further questions or want me to try something on my Pi4 then let me know.
Great Job! Thats exactly what I need at the right time. I want to measure the current consumption for the Pi zero W at different situations (radio off, wifi sta mode, wifi ap mode...). Your script does a lot of work for me. Thank you.
Hi Johannas

You're welcome, good to know you like it and it is useful to you. I hope your project goes well.
Hi Roboberry, I got the the hotspot on with with two red cross symbol. Now my phone detects the hotspot but is not getting any IP address and hangs. What could be the problem? Please help!
Hi Victor

As you are seeing the hotspots ssid it is probably something with dnsmasq.
The first thing is check that dbsmasq is disabled with
sudo systemctl is-enabled dnsmasq.service

if it says enabled then it needs to be disabled with

sudo systemctl disable dnsmasq

if that is ok then when the access point is active with the red crosses enter sudo systemctl status dnsmasq
it should say active (running) in green near the top if it is running otherwise it will say failed and show an error, which may give a clue to the issue. Possibly check /etc/dnsmasq.conf for errors against the guide text.

If this is no help you could try the installer. There is a link near the top of this article. Follow that guide , You don't need to change any settings as the installer will modify your setup and hopefully fix the issue.

Otherwise let me know how you get on with the suggestions above and I will look into it further for you.
Hi roboberry !

thank you for the awesome job. I've been using your script for a while and it is working perfectly.

I need to change some behaviour but I did not succeed yet. I want to have a static IP on eth0 so I changed the dhcpcd.conf file to give static info for my rpi such as:

interface enxb827eb****** (don't have eth0 don't know why)
static ip_address=192.168.1.41/24
static routers=192.168.1.1
static domain_name_servers=192.168.1.8

I always get SSH access with ethernet cable (when rpi is connected to a wifi or in AP). I also get SSH access when the rpi is connected to the same wifi than my computer.

The issue comes when the Rpi is in hotspot mode and I connect my computer to that AP. Then no ssh connection is possible. If I remove the modification I did in dhcpcd.conf file there is no problem to connect to the AP

I guess there is something to do with the fact that dhcpcd service is disabled when hotspot is ON but I don't get what I need to do to get my static IP on eth0 in any case. Some help would be really appreciated !
Hi Katawan

you're welcome, im glad you find it useful.

dhcpcd is only disabled for wifi, it is still managing ethernet, the setup doesn't change anything there.

from my setup you just need the ip line as the router will do the name server.


interface enxb827eb******
static ip_address=192.168.1.41/24

interface wlan0 (whatever your wifi interface is)
nohook wpa_supplicant

That works fine for me.

Your interface names are "predictable" by default the are non predictable. It is fine either way with just one ethernet and and one wifi interface but is more of a benefit if you had two ethernet or two wifi interfaces. Any way you can change it in sudo raspi-config - Advance - Network Interface Names: predictable is what you have, no predictable is eth0 wlan0.

let me know if that doesn't help and I will look into it further.
.
Thank you for the answer.

I make it works as expected by moving the line:
interface enxb827eb******
static ip_address=192.168.1.41/24

after the "nohook wpa_supplicant"

but now I see your answer I realize that it was probably failing because I don't have the line "interface wlan0" so the nohook was included into the enxb827eb**** interface


I'll try again with the "interface wlan0" information

Thank you for the help !
Simple Question. Say I change my wifi password. or I took my PI to my friend house, what will happen. do I need a cronjob for this? I would like to activate hotspot whenever PI is not connected to a AP. is it possible?
Hi Saqib

Yea that's possible, it is what it is designed to do. The cron timer is only needed if you don't want to reboot to switch between the router connection and hotspot setups.

As standard the Autohotspot script will only check for your router when the Pi is first started. So if you change your WiFi password or take it to your friends and then start the Pi up, it will go to a hotspot.

You only need the cron timer if you start your pi in range of your router and then without switching the Pi off, you go to your friends. When you are 2 minutes, for example, from your house the Pi will automatically reconfigure itself to a Hotspot.
Then with the Pi still running you go back home. 2 minutes later the Pi will deactivate the hotspot and reconnect to your router.

There is also an installer script, link at the top of the article. There is an option that will force it between your router and a Hotspot without a reboot, even when you are home.

Let me know if you need further details.
Thanks for this tutorial. Great insight into hotspot setup. I have my RPi setup as hotspot and Wi-fi router using RaspAp but I can only connect 1 device at a time. Using your script, could I have more than one device connected and able to see each other? Want to use RPi as a Wi-fi router on a boat to pass GPS data from iPhone to chart plotter on iPad. Not bothered by onward internet. Thanks.
Hi Dave

When the script is in Access point mode you can connect multiple devices to the WiFi access point and they can all see each other via their IP address. I have been able to use ssh from one Pi through the Access Point of a second Pi to a third Pi ok. I have also used VNC to see the third Pi's desktop from the first Pi routed through the second Pi's WiFi Access Point.
Doing this via a Hostname seems to be more inconsistent, but can be done with additional settings.

I have not used RaspAP but I am surprised you can only connect one device at a time.
I know it uses a custom dhcpcd.conf file so would need to be fully uninstalled before trying my setup.

How are your Iphone, Ipad communicating? I presume an app that expects to be on the same network.

If you need more detail then your welcome to email admin at this site.
Thanks for the reply. Yeah strange but cannot get more than one device to connect. Re: marine charts - the chart software listens for GPS data packets specifically from the GPS2IP app which in turn uses iOS gps chipset for position data and then broadcasts it. There are a number of ways to do this but is off topic for this thread. Suffice to say as long as both devices are on the same network, the apps see each other. I read your tutorial with interest as it shows a lot of what happens under the bonnet. Think I will have a play with your script and see what happens! 8-) Thanks again.
Hi Dave

You're welcome. That sounds like it should work fine. You can use option 2 on the installer and then use the manual guide to reference any of the setup.

If you decide you need a permanent access point rather than the auto one then the installer will swap them over in a few seconds.
Any idea on how to have a simple DNS server running on the created hotspot?
Here is my setup: one RaspberryPi creates Hotspot1, 2nd RaspberryPi and 3rd RaspberryPi connect to this hotspot.
The RPi that owns the hotspot can ping its clients by short hostnames, but its clients can't ping any of the other network devices by short hostname.
Hi Ovidiu

I have setup 3 pi's as you suggest. Pi1 Access point, Pi2 & Pi3 connect to Pi1. In my situation Pi1 & Pi2 could access the other 2 via hostname but pi 3 could only access pi1. So it is probably down to if the pi's have communicated previously.

Here is a solution:
/etc/hosts on Pi1 can hold a list of ip addresses and host names but as the ip is dynamic you can set static ip's and hostnames in /etc/dnsmasq.conf

Add to the config file the mac address of the pi and the hostname to assign with
dhcp-host=xx:xx:xx:xx:xx:xx,myhostname
ie dhcp-host=00:20:e0:3b:13:af,Pi1

or mac, hostname and ip with
dhcp-host=xx:xx:xx:xx:xx:xx,myhostname,myip
ie dhcp-host=00:20:e0:3b:13:af,Pi1,10.0.0.55

the ip has to be in range also set in the dnsmasq.conf file
dhcp-range=10.0.0.50,10.0.0.150,12h
Thank you for your help, this is useful :).
I solved my issue in a very similar way: I added another hosts file by doing this
sudo vim /etc/dnsmasq.conf
=============
no-resolv
no-hosts
addn-hosts=/etc/dnsmasq_hosts
=============
and in this new file I added the IP - hostname association.

Turns out that my problem was a bit smaller than initially thought. The issue was that everyone knows about everyone with a slight exception. RPi2 and RPi3 solve RPI1 (the hotspot) at 127.0.1.1 instead of it's real IP (10.0.0.5).
Your solution is actually more elegant as it doesn't require overwriting the hosts file.
Hi Ovidiu

You're welcome. Thank you for the feedback, useful for other users as well. I'm glad you have it setup as you need. enjoy :)
Great tutorial, thank you.
Please also include the following to it as others might face the same challenge:
If you have a firewall, you should open the port for DHCP, otherwise the client won't get an IP. E.g.
sudo ufw allow 67 # for DHCP
Hi Ovidiu

Thanks for the tip for firewall users.
what if you are using nftables? this is my issue - works / connects but no IP address, and I am using nftables
Hi "admin user"

The direct autohotspot script (on this page) does not use iptable so will work fine if you have nftables setup. An issue of no IP address usually means there is an issue with the config for dnsmasq. Double check the setup in dnsmsaq.conf and also run sudo systemctl status dnsmasq to see if it reports an error.

If you are using the other script with internet access then it won't work with nftables, I believe it causes a conflict.
I plan to add a detection for nftables and enable where required but this is not currently available.
My bad!

I forgot to add 10.0.0.1/24 to nftables SAFE_TRAFFIC_IPS.

How could I change the wlan network ip address from 10.0.0.1 to (for example) 192.168.4.1? - I have tried this but no luck.
Hi "admin user"

The access point ip address is changed in the autohotspot scripts and dnsmasq.conf.

in /etc/dnsmasq.conf change the ip range that connected devices can have from
dhcp-range=10.0.0.50,10.0.0.150,12h
to
dhcp-range=192.168.4.50,192.168.4.150,12h

then in /usr/bin/autohotspot
change the ip address

createAdHocNetwork()
{
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 10.0.0.5/24 brd + dev "$wifidev"

to

createAdHocNetwork()
{
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 192.168.4.1/24 brd + dev "$wifidev"


after a reboot 192.168.4.1 will now be the access points ip address.
First, thanks for figuring this out. I have a headless Pi Zero W running Raspberry Pi OS Buster lite and wanted the Pi Zero to put up an AP when the Pi Zero was unable to connect to any of the networks defined in wpa_supplicant.conf 30 seconds after boot.

I followed your instructions except I did not create a systemd service and I did not modify /etc/dhcpcd.conf

My simplified script based on your ideas is a follows

/usr/local/bin/ap-up.sh
#!/bin/bash

sleep 30

if [ ! $(iwgetid -r) ]
then
wpa_cli terminate
ip link set dev wlan0 down
ip addr add 10.0.0.5/24 brd + dev wlan0
ip link set dev wlan0 up
dhcpcd -k wlan0
systemctl start dnsmasq
systemctl start hostapd

fi

I opted to start up my /usr/local/bin/ap-up.sh script in /etc/rc.local instead of using systemd,

My /etc/rc.local is as follows
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi

# set up access point if no network connection
/usr/local/bin/ap-up.sh >/dev/null 2>&1 &

exit 0
Hi Vernon

Thanks for sharing your setup for a autohotspot.

It is possible to delay that start of the autohotspot service using a systemd timer.

If you create a service called autohotspot.timer in /etc/systemd/system/
with this code

# Autohotspot Delayed startup
[Unit]
Description=Runs the autohotspot.service 30 seconds after boot up

[Timer]
OnBootSec=30 s
Unit=autohotspot.service

[Install]
WantedBy=basic.target

then disable the autohotspot.service and enable the autohotspot.timer

The script will be started 30 seconds after boot though you will need to add in the dhcpcd.conf details again as you will get two ip addresses when the hotspot is active.

rc.local is not fully supported in favour of systemd now.

If your not happy with using systemd you can use a cron to run the /usr/bin/autohotspot script after boot
@reboot sleep 30 && /usr/bin/autohotspot
This will need to be in your root crontab though.
I apologize for not being clear. My script assumes a Pi Zero W with a fresh, latest Raspberry Pi OS lite install and has already been configured to successfully connect to the local network via its internal WiFi. The only time my script gets executed and sets up an AP is if the $(iwgetid -r) command in my script returns a NULL indicating that the Pi Zero W was unable to connect to the local wireless network. Therefore, /etc/dhcpcd.conf should not be modified.

Since my script does not interfere with the out of the box Pi Zero W wireless network connection process, it is easier to debug during headless operation. Note that I have never connected my Pi Zero W to a keyboard or a monitor.

A couple of tips for headless testing.

1) Run ap-up.sh from the command line before invoking it from /etc/rc.local.
a) sudo apt-get install screen
b) screen
c) sudo shutdown -r +2
d) sudo /usr/local/bin/ap-up.sh >debug.txt 2>&1

If you lose your lan ssh connection to your Pi Zero W and no AP appears, the Pi will reboot in 2 minutes, reconnect to your network and you can look in file debug.txt for clues. This saves the wear and tear of otherwise having to the cycle power to the Pi Zero W in order to regain access.

2) You can isolate your Pi Zero W from your network to see if it generates an AP by powering it up in a Faraday cage - e.g. your microwave oven.

3) Since most OSes including most Linux distributions run Apple's Bonjour out of the box, you can access your Pi by typing

ssh pi@raspberrypi.local

instead of using the IP address assuming you have not changed the default username and host name. This allows you to use the same ssh command whether the Pi Zero W is connected to your lan or you are connected to the Pi Zero W AP.

Thanks again and best wishes
HI Vernon

Thanks for the update, absolutely understand keeping it simple for debugging and reducing failure point.
I like the microwave tip :)

The dhcpcd mod is just to stop dhcpcd generating an ip address when the AP is starting. It confused streaming services as they started too soon to get the dnsmasq ip. It will work fine without the mod if you don't broadcast a stream from boot.

I have found that the host name is not 100% reliable connecting to my router or as an access point, so I have to use the ip address but 98% of the time i use the host name to connect with.

Thanks again for your script.
Beware of the Windows styled newlines. They can cause the interface bouncing up/down and other fishy network behavior.
Details available here: https://gist.github.com/neaxi/cbd68f9de00efb9ce1c5145d875de163
Hi Q, thank you for the bug report.

Yea I was aware of the windows newline issue, the next line in the code "wpassid=$(echo "${wpassid//[$'\r\n']}")" removes the windows CR LF from the results of the awk sequence. Then the ssids are passed to do the checking. I have redone some checks tonight to make sure it is still working.
I have created wpa_supplicant.conf in wordpad and saved it as windows txt and uni txt and also done the same in notepad and saved as text.

The current autohotspot script handles both the windows encoded files with \r\n but the uni encoded file was not readable and went to a hotspot.
Can you let me know what windows program and format you saved your file in please.

Though it works i prefer to have the ssids read by one command line so thanks for the suggestion.

The error -52 has only appeared since Buster and just seems to happen occasionally and then clears. So this is specifically checked for along with other errors such as busy and readonly. These clear within a second and the scans and script them works fine.
1. Thank you for such a quick response

2. I've written the file using Notepad++. Feel free to grab a copy here: http://neaxi.cz/FTP/win_wpa_supplicant.conf
The issue I've encountered is the "wpassid=$(echo "${wpassid//[$'\r\n']}")" receives a bad string from the previous AWK, which is the reason, why the \r\n has to be handled earlier, so I'm currently cleaning it up prior ORS concatenation.
Modified command is available under the Gist link in my first post.
I've replaced:
"awk -F'ssid=' '{ print $2 }' ORS=','"
for:
"awk -F'ssid=' '{ print $2 }' | sed 's/\r//g'| awk 'BEGIN{ORS=","} {print}'"

3. Another issue occures when the SSID contains special chars ("-~" in my case).
This line "if (echo "$ssidreply" | grep "$ssid") >/dev/null 2>&1" need to be modified to ensure grep won't attempt to interpret the SSID as regex or cli argument.
Current:
$ iw dev wlan0 scan | grep "-~={}=~-"
grep: invalid option -- '~'

Proposed modification with "grep -F --":
$ sudo iw dev wlan0 scan | grep -F -- "-~={}=~-"


4. I've reinstalled the hotspot using your AutoHotspot-Setup script and except the issues mentioned in #2 and #3 everything works like a charm. Great work, thank you!

(I agree the error -52 is a non-issue and you're already handling it. I've just archived the ouput for myself as "encountered errors")
Hi Q

Thanks for the wpa file. I did think that a ~ in the ssid was usual but it look like a place holder for code so I can see your issue. Thanks the Grep tip I will implement your suggestions and make it more robust.
I'm glad you find the script useful, once modded :) and appreciate your input.
Hello,

great and details tutorial.

I am using Raspi 4 (not connect through ethernet, not using any dongle) and was up to the point of testing. After I ssh to the Pi, i tried sudo raspi-config, and navigate to network options, and then to wireless LAN. Then it gives me an error of
"Could not communicate with wpa_supplicant"
and followed by
"There was an error running option N2 Wireless LAN".

Any suggestion how I can configure the WiFi, and reboot the device so i connects to the WiFi network instead of staying as hotspot?

thanks a lot!
Hi Kesepio

When the Pi is in Access Point mode it shuts down wpa_supplicant which would be why you see the error.
There are two ways you can add a new wifi network. The first is to edit /etc/wpa_supplicant/wpa_supplicant.conf and add the new wifi network in manually. Then rerun the autohotspot script sudo /usr/bin/autohotspot and it will connect to the new wifi network. (autohotspotN for internet enabled script)

A bit manual.

Alternately I have an installer script, there is a link at the top of this article and at the bottom of the home page.
If you download that script, you don't need to install anything from it but it has an option to setup a new wifi network over ssh while the pi is in access point mode. Option 5. This will list SSID's in range which you can select and then enter the password. This is just limited to SSID's that don't require a username login such as public wifi'

You can also change the Pi's Access Point SSID and Password.

This would be the simpler option.
Thanks, roboberry!!

The script works fantastic!

I have another question – I want a python script to check after system reboot to see if it is in hotspot mode or normal wifi mode on my raspberry pi 4 and pi zero. I tried checking the hostname with

check_output(['hostname', '-I']).decode(sys.stdout.encoding).split()

to see if it matches the 192.168.50.5, but it seems to return nothing unless I am actually ssh in and run the script again. Running socket.gethostbyname(socket.gethostname()) seems to always return 127.0.1.1 for me. I am at a lost if there is any where I can check if the Pi is running hotspot mode or otherwise. The reason why I am doing is because I have a small LCD attached, and would like to show info/indicator of the mode.

Any suggestion or advise very much welcome.
Hi Kesepio

The hostname -I should work. You can try checking if hostapd is active or not with
sudo systemctl is-active hostapd.service

it will respond active of hostapd is running meaning the access point is running or inactive if the pi is connected to a router.

you can also try the opposite and see if wpa_supplicant is running which will mean you are connected to a router
wpa_cli -i wlan0 status

will show "failed to connect ...." if the access point is running or give a load of stats about your connection to a router. If "ip-address" exists then you have a router connection over wifi.

I have tested python via ssh and directly on the Pi with a screen and got results with both. I won't be exactly how you have it but it looks to work with an IP for both lines.

import os
import subprocess

print(subprocess.check_output(['hostname', '-I']).decode().split())
print(os.system("hostname -I"))
Hey! I wondered that is it can be used for setting up ssid and password when raspi goes to another wifi area. And assume that i am far away from raspi.
Hi Emre, You would have to add a new ssid in /etc/wpa_supplicant/wpa_supplicant.conf via ssh and then reboot or run /usr/bin/autohotspot.

If you use the installer also on this website there is an option to add a new ssid
https://www.raspberryconnect.com/projects/65-raspberrypi-hotspot-accesspoints/183-raspberry-pi-automatic-hotspot-and-static-hotspot-installer

you would have to be near the Pi, within wifi range to do this though.
THIS IS FANTASTIC!!!!
This is even better than the solution I was originally looking for!
I was just trying to setup my R-Pi as a Hotspot so I could connect to it via SSH with my Android phone, but I kept getting socket connection timeouts on all my Android SSH apps and I had no idea why :-(
This is the only place where I found reference to the 'bug' where you have to turn off mobile data on the phone to make SSH work.
The project I just built is a panning time lapse camera, and it's in a waterproof case so I needed WiFi and SSH to adjust the camera and stepper motor settings in my scripts while out in the field. Now I can connect to both my home router AND my Android phone!
Thank you so much for this work!
You really should tell the folks over at RaspberryPi.org to post this to their WiFi documentation page... I can think of so many scenarios where people would need this setup.
Hi LucidEye, You're welcome, I'm glad you have found it useful. It is a bit of a pain with the Android SSH issue. if you have a data manager you can set it to not use data with the SSH app, but I just still disable data when required.

The script was originally developed so I could do simple static timelapse as well while away. So it's good to hear it's being used for a panning setup.

The original versions of the script is several years old which was posted on the RaspberryPi.org forums, but it has been developed a lot more since then.
Works for me, great script!
If I want to create the WiFi hotspot not with the internal WiFi chip of the Raspberry Pi 4, but with a WiFi dongle connected to a USB port, what do I have to change?
Best regards
Hi Lars

Thanks, The setup can be changed to wlan1, though usually the case that the usb wifi will be wlan1 it is not guaranteed. The operating system will decide which device is wlan0 and wlan1 at boot. Using the predictable interface names (activated in raspi-config) will make it always the usb wifi but it will get a unique device name starting with wl

Also if you intend to use wlan0 at the same time it won't work with this script as it will be disabled from connecting to a router.

To change to wlan1 change any references to wlan0 in /etc/hostapd/hostapd.conf
/etc/dnsmasq.conf

then in /usr/bin/autohotspot near the top find this entry

wifidev="wlan0" #device name to use. Default is wlan0.
#use the command: iw dev ,to see wifi interface name

and change wlan0 to wlan1
Hi,
thanks for your fast reply!
For 2.4 GHz it is working now, I guess.
What do I have to change in hostadp.conf if I want to configure it for 5 GHz WiFi? Do I only have to edit the channel and the hw_mode=ac? (I think the WiFi stick supports ac WiFi standard)
Regards,
Lars
Hi Lars

I did have a 5ghz config but I can't find where I put it and it's been a while since it set it up but from a quick look around the net you need

hw_mode=a
channel=36
ieee80211ac=1
wmm_enabled=1

try that, if that doesn't work unfortunately you will need to google it.
Hi Robert,
I tried to follow the guide. I use an rpi4 but the wifi does not work at the reboot and I don't even see the hotspot
Hi Valeria

If you are getting no network or Hotspot at reboot then either the autohotspot.service is not enabled or has failed to start the script.

Firstly check the service is enabled
sudo systemctl -all list-unit-files autohotspot.service

It should show autohotspot.service enabled
If not then enable it with
sudo systemctl enable autohotspot

If that was enable then see if you can run the script manually.
sudo /usr/bin/autohotspot

If that runs without errors and starts your wifi then check the script has been enabled to run

sudo chmod +x /usr/bin/autohotspot

and then reboot and see if that works.


There is an installer available at the top of the page and on the home page if you would like to try that.
Quoting scars:
ok the script wont work because i am using a kali pi...
My problem is the Hotspot atribute a IP to my android or notebook..


i mean do not atribute IP
The RPI connect on router on home, and create a hotspot outside... i guess that i cant get ip adress... where is the problem?
Hi Scars

Could you give me some more detail on your issue please. Is it the connection to your router or the hotspot that you have an issue with. If it's the hotspot do you see the RPiHotspot ssid but can't connect from a phone or laptop? Have you made any modifications to the setup?

Most issues are to do with config errors. The installer script will reinstall the config and setup as required. There is a link towards the top of this page and on the home page, it's simple to use.
ok i will try the script... but i just have problems to connect with my cellph to RPIhotspot...
In home he connects to home wiki normally..

this script is amazing.. great work
Hi Scars, Thanks.
On android you have to switch off your data to connect via ssh. This is to do with Android and not the PI. Unless you can deactivate data just for the SSH program. VNC is fine with Data on.

If the issue is android ssh then the installer won't help. If it's generally connecting to your phone then it should help. Otherwise let me know the details and I will look into it.
ok the script wont work because i am using a kali pi...
My problem is the Hotspot atribute a IP to my android or notebook..
Hi Scars

The script is setup for Raspbian. If Kali is using a different network manger to dhcpcd then it won't work as it disables wifi to bring up a hotspot. If you have another network manger then it will still be running and the hotspot will fail.

If the /etc/dhcpcd.conf file was blank or you installed dhcpcd then that will be the issue.
# Defaults from Raspberry Pi configuration
hostname
clientid
persistent
option rapid_commit
option domain_name_servers, domain_name, domain_search, host_name
option classless_static_routes
option ntp_servers
require dhcp_server_identifier
slaac private
nohook lookup-hostname

#denyinterfaces eth0 wlan0 #BRIDGED

nohook wpa_supplicant

i got this on my dhcpcd.conf file... i think that i just add the last line "nohook wpa_suppliant" like the tutorial said..
Some ideas how i can resolve this? sorry for spam your comment area
Hi Scars

I have compared the entries to Raspbians. The main differences are
option ntp_servers (not in Raspbian)
nohook lookup-hostaname (not in Raspbian)

Your dhcpcd.conf is not the file supplied by dhcpcd by default so you may have other software causing conflicts.

nohook wpa_supplicant (is ok, from the guide)

you can check if dhcpcd is running and presumably your default network manager with:
sudo systemctl -all list-units dhcpcd.service

this should show a line:
dhcpcd.service loaded active running

If it shows anything else then you have some other network manager running that the autohotspot script won't work with.
The setup has only been tested on Raspbian, I have not used Kali to know how the network is configured. Even if dhcpcd is the network manager, there may be other settings that need changing for the autohotspot script to work properly.

I do intend on making a script for Kali and other distributions available at a future date, i need to do some more changes on Raspbian before I work on other distributions.

I will test the default setup on a Kali image at some point soon just to confirm I doesn't work out the box and if there is a quick fix or if it needs more work to get it working.
Awesome tutorial and script! This is working great for me. I have been playing with getting a web page set up to change the ssid and static ip of the client in dhcpcd.conf and wpa_supplicant. Do you know of anyone who has done that? The idea being that you can log into the pi while in AP mode, change the ssid and IP for client mode, then connect to the client ssid.
Hi Matthew, Thanks.
The installer that that is referenced at the top of this page and the home page can also add a new ssid and change the password of an existing one. It can also then switch the pi from the hotspot to connect to the router. So other than setting a static ip a can be used for that.

I have been contacted by someone who was going to do something similar as what you suggest but yet to get an update, i will follow up.
You used the words ad hoc and hot spot almost interchangeably. Is this not wrong? Ad hoc = "non infrastructure" and hot spot = "infrastructure". Thought they were very different?
Hi Stev

Yep I get what you are saying and they are different.
It was originally designed so I could connect my tablet to my PI only without internet, so used as a adhoc direct connection for ssh, hence those references.
I made it available a few years ago on the website and slowly people asked for more features so the script has grown beyond it's original use. The references to hotspot as been added as the script developed. I just haven't changes the references. Noted :)
How could I modify this to just do something manually have a "home" script and an "away" script on my desktop? I want things to operate normally as if there was no hotspot at home, but switch to a setup that RPi is always at "myRasPi.local" and running VncServer. It sets wlan0 to a static address and disables wpa_supplicant for wlan0. It puts an address range in dnsmasq.conf and puts the SSID and PW in hostapd. I know networking, but really not much about the Pi and how it networks. Thanks for great work!
Hi Fred D,
If i'm following correctly you would only need two scripts if you wanted to switch to the hotspot while still in range of your home network otherwise the hostname, vnc and change of the ip can be done to the existing setup.

If you do need the hotspot while at home i'm about to release a setup script and installer that can force between the network and hotspot regardless of your location, should be within a week.

to change the hotspots hostname go to /etc/hosts
and enter
10.0.0.5 myRasPi
though not all devices seem to recognise the host name for the hotspot, so this may or may not work for you.

The script already sets a static ip of 10.0.0.5 for the hotspot and wpa supplicant will be disabled.

if you need a static ip for "Home" then set that in /etc/dhcpcd.conf. There is and example at the bottom of the file.

Changing the hostapd password would need to be done manually in the hostapd.conf file.
For the dnsmasq range that needs to pair with the ip in the autohotspot script so if you change the dhcp-range to dhcp-range=192.168.1.50,192.168.1.150,12h then the ip in the autohotspot script would need changing
ip a add 10.0.0.5/24 brd + dev "$wifidev" to ip a add 192.168.1.5/24 brd + dev "$wifidev"

For RealVNC that is installed as standard in raspbian. and enabled in the Raspberry Pi Configuration.
You can enable and disable it with
sudo systemctl start vncserver-x11-serviced.service
sudo systemctl stop vncserver-x11-serviced.service

so adding these line to the script will start and stop vnc

Last line of sections:
createAdHocNetwork()
and
KillHotspot()

Hopefully this helps. Your welcome to email if you have more detail.
That's exactly write. I may take you up on emailing if I need more help. I'll wait to see your new script. In general, I can live with the "automatic" method of connecting to home while home and becoming a hotspot when away so my phone can connect to software running on the Pi. (It controls model trains). I thought there might be simple methods, like disabling the 2 services and enabling them again, and did find something that looked like about 6 lines to go to wifi mode and about the same to go to AP mode, but I need to learn more about all these settings. It could be as easy as keeping a backup copy of a .conf file and switching between them in a script that also enables and disables the services. I may not *need* to do the hotspot at home, but I would like it for testing (rather than having to turn my router off). And there are times where I may want to have a separate network for the train controllers that doesn't go through the home network. Thanks again!
Hi Fred
Just to let you know, I have added an installer script to the home page, this has an option that forces the autohotspot to a hotspot even when you are at home. You can then switch it back with the same option.

If this doesn't quite do the job then let me know what you need and I will see what I can do.
I just wanted to reply with a thank you! :)
my pizero turns into a hotspot just fine, however when i apply a wifi network into the wps_supp file, then it does not detect it upon boot and enables hotspot again.
Hi Saqib Khan

The Pi will go back to a hotspot if the Pi can't connect to the router. The most common reason is either the SSID line or Password line is not correct. Also check they are in quotes "". There is an example of the file just above these comments. Also check the top 3 lines are correct with your correct country in country=

The script doesn't effect how the pi connects to your router in network mode and works the same way as if the script wasn't installed as far as connecting to your router.
If that connection fails then it will go back to the hotspot after 20 seconds.

If your wpa file is fine then come back and I will see what else we can look into.
it turns out the problem was with the country. my wpa file sets the country to US, and in my hostpad i also have country set to us..and it still did not work. i ended up going into raspi-config > Localization and set the country manually. and now its working.
Hi Saqib Khan

The localisation settings change the wpa file and probably other stuff, though I would expect the wpa file would be fine with a manual entry. Anyway i'm glad you have it sorted now.
actually i am wrong. I installed this script on new SD card, did set the country and it wont switch to client mode.
Hi Saqib khan

Ok a few things to try.
If there is a comma in the SSID name then it will get split into two and won't be detected. Spaces are ok in the SSID.
If you used a windows text editor to create the wpa_supplicant.conf file in the boot folder then there may be carriage returns causing issues. Recreate the file in Linux or use dos2unix to strip them out of the wpa_supplicant.conf file.

If that doesn't help then disable the script and confirm you get an connection to your router ok. Then if you let have an example of your ssid i will see if it's doing something strange with it and splitting it.
To disable the setup:
sudo systemctl disable autohotspot
in /etc/dhcpcd.conf put a # in front of nohook wpa_supplicant.
then reboot

to re enable the script then just remove the # from the nohook line and enter
sudo systemctl enable autohotspot
then reboot
Hello roboberry,
thanks for this tutorial. Unfortunately I have the same problem as "saqib khan". I checked all the tips you gave. Unfortunately my RaspiZeroW does not connect to my WLAN but always creates a hotspot. When I deactivate the script it connects to my WLAN. Do you have another idea I missed?
Thanks a lot
Konsorte
Hi Konsorte

If non of the other tips have helped can you post or email an example of the ssid line in your wpa_supplicant.conf file just in case it's being split into two lines.
It will just be how the scripts filtering your SSID format from the rest of the file.
Hello roboberry,
thanks for your answer. Here is my wpa_supplicant.conf:
_______________________________________________________
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=DE

network={
ssid="RouterWLAN"
psk="??99882211!!"
}
_________________________________________________________

Here is my installation routine:
1. new clean RaspbianBusterLite installed on Rasperry Pi Zero W
2. Raspi-config -> Location DE; SSH on
3. connected with PuTTY from Windows on PiZero
4. your tutorial
5. reboot
6. PiZero starts Hotspot but does not connect to RouterWLAN
Hi Konsorte

Thanks for the file and steps taken.
Out of interest, was your wpa_supplicant file created in windows and placed in the boot folder or with raspi-config on the pi?

There is no reason why your ssid would not be picked up correctly with the script.
I just tried creating wpa_supplicant in windows, if done in notepad it works fine on the pi with the autohotspot script but wordpad fail because of the extra Cr characters.

Maybe backup your wpa_supplicant.conf file and delete it. then in sudo raspi-config - Network Options - WiFi
add your details, which will create a new file and try again.

Please let me know if this helps so I can find the cause.

ps bonus points for spotting the service file text :)
Hello roboberry,

your script works! I have created a hotspot with my smartphone and with my old router. The RaspiZero connects to both as it should. Only with my home network router (FritzBox7590) it does not. I haven't found out why yet. No matter what settings I make, the Zero will not connect to the FritzBox.
Thanks again for your help.

@saqib khan
Thanks for your help. "cat -A" doesn't show any ^M in my file.

When I find the error with my FritzBox I will post it here.

Thanks again to you all!
Hi Konsorte

That's a bit odd. The SSID would not be an issue. Unless there is some reason your router is very very slow it should give the Pi and IP within 20 seconds. You can increase that here:
ChkWifiUp()
{
echo "Checking WiFi connection ok"
sleep 20 #give time for connection to be completed to router

change sleep seconds from 20. But I would be surprised if that's it.

I added a line to the script at the weekend to remove Cr from wpa_supplicant so if you re-download the autohotspot file and enable it, sudo chmod +x /usr/bin/autohotspot

then try again.

If you can't find a solution I will send you the autohotspot script with more feedback so you may be able to see the issue.
I was able to resolve the issue. I generated wpa file using windows. to verify this do the following in terminal "cat -A ". if it shows ^M then this is your problem.
This guide and the scripts were very helpful. Thank you!
Hi Michael, you're welcome. I'm glad you have found it useful.
Here are the relevant config file sections. Thanks!

-------------------------
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="AP4999test"
psk="SillyPassWord4Testing66e6"
}

-------------------------------
# Static IP configuration
interface eth0
static ip_address=192.168.1.185/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4

interface wlan0
static ip_address=192.168.1.184/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4


# It is possible to fall back to a static IP if DHCP fails:
# define static profile
#profile static_eth0
#static ip_address=192.168.1.23/24
#static routers=192.168.1.1
#static domain_name_servers=192.168.1.1

# fallback to static profile on eth0
#interface eth0
#fallback static_eth0

#### FOR AUTOHOTSPOT ####

nohook wpa_supplicant


-------------------
#2.4GHz setup wifi 80211 b,g,n
interface=wlan0
driver=nl80211
ssid=RPiHotspot
hw_mode=g
channel=8
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=777666testx
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
rsn_pairwise=CCMP

#80211n - Change GB to your WiFi country code
country_code=US
ieee80211n=1
ieee80211d=1
First, great work on the scripts & tutorials. Thanks! My longer term goal is to use your autohotspotN script with a Pi Zero W that I use occasionally with an ethernet adapter. In that case, it would be useful, to provide Internet access to the Pi and any connected hotspot clients. Right now the script won't work for that since eth0 doesn't exist of course until the wifi dongle is plugged in, but the modification should be straightforward. Currently I'm unable to get the hotspot working. On my first attempt it appeared but kept connecting and disconnecting. Now it no longer even appears. Sometimes the script gives no errors (e.g., says Activating Hotspot). Other times there are errors, one of which can be cleared by flushing the ip. In any case, the hotspot never appears, my static ip ethernet connection is broken (as is my static ip wpa_supplicant wlan0). I have to go back to the sdcard and reenable the router AP and go back to AP mode to reestablish. I suspect my static ip configurations may be at the core of this, but I'm not sure where to begin. Any suggestions? Thanks very much!
Hi A RPIZW User,
Your welcome. Regarding the eth0 setup. you say "eth0 doesn't exist of course until the wifi dongle is plugged in," If you are adding a network device that the PI believes to be eth0 then that's fine but if you mean a wifi dongle that would usually be wlan1 but is remapped to eth0 that will fail with this setup. This is because the hotspot disables wpa_supplicant that you would need for wlan1/eth0 to connect to your router. This setup works with a permanent hotspot on wlan0 and routed network to wlan1. As long as the Pi thinks eth0 is wired then it will be fine.

It sounds like something is interfering with the config as you shouldn't need to flush the ip yourself and this is usually a result of the network wifi via wpa_supplicant being enabled while the hotspot is active. This can be if /etc/network/interfaces has network setup or dhcpcd has been enabled for wlan0 while it's in hotspot mode.
Usually if there is no outside other process interfering and there is a hicup you can just run /usr/bin/autohotspot and it will usually resolve it.

Check you only have one ip address in hotspot mode, ip addr
If you have two ip addresses then both the hotspot and network wifi is enabled. The connection to the router will always disrupt the hotspot.

Your static config is fine. That is only active on network mode as dhcpcd for wlan0 is shutdown in hotspot mode.

Let me know if you have additional config that may cause an issue. Your welcome to email me details of what happens and config file and I will look into it.
admin@ this site

Just an extra note, wpa_supplicant.conf should have the country set. usually done with the localisation settings in raspi-config or "Raspberry Pi Configuration" in the Desktop menus
Thanks for your reply! I'll look this over and send you an email, then when this is all sorted out I'll report back here to share results with everyone. Tnx again.
Hi RPIZW User,

Your config file looks fine. Can you check hostapd is still disabled. This should be done in network mode.
This command will show if if hostapd is enables, disabled or masked. It shouldbe disabled.
sudo systemctl -all list-unit-files | grep hostapd

The N version of the script works fine on a PiZero even though it has no eth0. DHCPCD will enable Eth0 once the adapter is connected so it will work from the Pi through ETH0. What I don't know is if the hotspot routing will just work to give internet access to devices connected to the hotspot or needs resetting.

I will have to disable eth0 on a full pi and test that one out and let you know.
pi@raspberrypi:~ $ sudo systemctl -all list-unit-files | grep hostapd
hostapd.service disabled
hostapd@.service disabled
pi@raspberrypi:~ $

Hmm. What is hostapd@ ? Suspicious. Thanks!
Hi RPIZW User,

hostapd@ is fine, its for alternate setups.
Can you confirm if you copied the autohotspot script from the webpage or used the download link. If you done it out of the webpage can you try from the download link, you will need to redo sudo chmod +x /usr/bin/autohotspot. Also which image of Rasbian Buster are you using, Raspbian, Raspbian Lite or Noobs.
I believe I copy/pasted since that was the fastest way to grab the text and get it over to the RPI. I'll try the download link. This is on a
Buster Lite system. Thanks!
Copy & Paste is fine, just sometime webpage selections go a bit wild so I just want to check the script is complete. I use full Raspbian so I will set it up on lite just to check there is no difference and get back to you.
Ah, I see my typo in the original message regarding eth0. I meant to say that eth0 isn't present until the ETHERNET dongle is plugged in. Oops. That should make more sense. Currently the N script would presumably fail when it can't find eth0 to check when the Ethernet dongle isn't plugged in. Thanks again.
/etc/network/interfaces file is empty except for the initial comments and the source directory line for /etc/network/interfaces.d (which is empty).

Contents of dhcpcd.conf:

# Allow users of this group to interact with dhcpcd via the control socket.
#controlgroup wheel

# Inform the DHCP server of our hostname for DDNS.
hostname

# Use the hardware address of the interface for the Client ID.
clientid
# or
# Use the same DUID + IAID as set in DHCPv6 for DHCPv4 ClientID as per RFC4361.
# Some non-RFC compliant DHCP servers do not reply with this set.
# In this case, comment out duid and enable clientid above.
#duid

# Persist interface configuration when dhcpcd exits.
persistent

# Rapid commit support.
# Safe to enable by default because it requires the equivalent option set
# on the server to actually work.
option rapid_commit

# A list of options to request from the DHCP server.
option domain_name_servers, domain_name, domain_search, host_name
option classless_static_routes
# Respect the network MTU. This is applied to DHCP routes.
option interface_mtu

# Most distributions have NTP support.
#option ntp_servers

# A ServerID is required by RFC2131.
require dhcp_server_identifier

# Generate SLAAC address using the Hardware Address of the interface
#slaac hwaddr
# OR generate Stable Private IPv6 Addresses based from the DUID
slaac private

# Static IP configuration
interface eth0
static ip_address=192.168.1.185/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4

interface wlan0
static ip_address=192.168.1.184/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4

nohook wpa_supplicant
Hi, I have hotspot up and running but the only problem is that I get no ip assigned on my pc when I connect to the network. Any idea how can one solve this issue?
Hi Lukas

I take it you can see the hotspots ssid of RPiHotspot from your PC. If so can you connect to it and are prompted for the password?

If so I take it you can't make a ssh or vnc connection from your PC?

On the Raspberry Pi if you enter 'ip addr' are there one or two ip address for wlan0?

if there are two then check the line "nohook wpa_supplicant" is in /etc/dhcpcd.conf

Check that the details in /etc/dnsmasq.conf are for ip dhcp-range=10.0.0.50,10.0.0.150,12h

Run the autohotspot script manually and check the feedback for errors.
sudo /usr/bin/autohotspot

Are you using a USB Wifi adapter? if it uses the RTL8188EUS chipset it is not compatible with Hostatp and not the same as the Pi's wifi. There is an alternate version of hostapd that can be used.

If you can give me some further information on your setup and what happens I will try and find the issue.
Hi Roboberry,

sorry for the limited information I gave you before.

I do see the SSID from my PC. I am also able to connect to it but get an Automatic Private IP.
This is also true for wlan0 on rpi.

This is the output of a script:
SSid's in range: BSS 34:da:b7:8f:a4:59(on wlan0) SSID: ZTE-92DKEV
Device Available Check try 0
Device Available, checking SSid Results
Hostspot already active

I also had to add the following to the /etc/network/interfaces for wpa_cli to work:
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

I am using raspberry pi 4 with internal WiFi

hope it helps.
Hi Lukas
No problem. The issue will be from the /etc/network/interfaces entry. This will activate a second network manager which is in conflict of the PI's main network manager, dhcpcd. The interfaces file is depreciated in Raspbian. The entry activates wpa_supplicant which is used to run the network connection to your router and will override the hotspot. So your pi has reconnected to the router via the second network manager.
If you remove the changes to the interface file it will work again.

In hotspot mode wpa_cli won't be available as wpa_supplicant is shutdown for wlan0 so that Hostapd and dnsmasq can manage the hotspot. if you need to scan for wifi signals and see wifi setups you can use iw
Once your back in network mode then wpa_cli will be available again.

Can I ask the reason wpa_cli is being used while in hotspot mode? In case there is an alternative option or maybe there is some setup I need to consider if possible.
Hi Roboberry,

The reason behind that is I wanted to use the RaspAP project for connecting to the desired network and your script if the network is not available. The problem is, RaspAP uses the wpa_cli interface. The hotspot works without any issues once I add a static ipaddress to the interfaces:

allow-hotplug wlan0
iface wlan0 inet static
address 10.0.0.5
netmask 255.255.255.0
network 10.0.0.0
broadcast 10.0.0.255

Any ideas?
Hi Roboberry,
What I want to accomplish is that once the wifi fails (eg. no accessible wifi is around) create a hotspot. Once you connec to the raspberryPi network, it will automatically open a webpage for you with the RaspAp project to allow you to select a new WiFi. RaspAp uses the wpa_cli interface so this is why I would like to support it.

When I add the static IP address to the network/interfaces, everything works fine except it tries to use the same IP not only for hotspot but for the WiFi connection as well...
Hi Lukas

Ok, understand why you would want to use the web interface. I do have a script to add new wifi networks which I will be releasing soon as part of an installer but a web interface is easier.

As mentioned the entry in /network/interfaces is activating a network manager and though it may seem it works fine it is running separately to my script so the config will compete with the hotspot setup and not function properly. The interfaces file needs to be cleared for the autohotspot to work as designed.

I have looked at the RaspAP files on github and they are using hostapd and dnsmasq for the hotspot but have some custom setup so im not sure it's compatible.

I will install and RaspAP and see what it's doing, in the next couple of days and get back to you.
Hi roboberry,

How about, (by combining our knowledge) we'd create a deb package containing the GUI web interface together with the scripts for the Autohotspot management? I think it would be both easier for the end-users to install and work with.

This way there would be a possibility to manage the IP addresses and DNS settings.

I am not sure who's approving the comments but in case you have my email, do not hesitate to contact me directly.
Hi, add dhcpd installation instruction. I spend two hour trying your script and it doesn't work because I don't have dhcpd installed in my system (Odroid XU4 with ubuntu mate 16.04). Now it works great!!!! thank
Is there a way to get static IP address when in client mode?
Hi Leonardo

I'm glad you have it working on Ubuntu, I have not tried it with other distro's. The guide is written for Raspbian which uses DHCPCD as it's default network manager. Different versions of linux use different network mangers and setups so I can't guarantee they would work even if dhcpcd was installed. As it may conflict with other network setup.

You can setup a static Ip for network mode in the dhcpcd.conf file. There is an example in the file itself. if you google "dhcpcd.conf static ip" you will find guides on what you need to do.
Rob, what about configure two wifi network (two different priorities) and a fallback as AP?
Currently I have configured wpa_supplicant like this:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=AR

network={
ssid="elgarbe"
psk="27825719"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
id_str="mi_casa"
priority=1
}

network={
ssid="cluster"
psk="27825719"
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
id_str="cluster"
priority=2
}


then mi interfaces is like this:

# interfaces(5) file used by ifup(8) and ifdown(8)
# Include files from /etc/network/interfaces.d:
#source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback


allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf

iface mi_casa inet static
address 10.10.10.5
gateway 10.10.10.1
netmask 255.255.255.0
dns-nameservers 8.8.8.8 10.10.10.1

iface cluster inet static
address 192.168.0.5
gateway 192.168.0.1
netmask 255.255.255.0

so, this way I get two possible AP to connect to and each one with static IP. Now I add your script and when I boot my Odroid it work ok, if any of my AP are up it connect to them (according to priority) else it create an AP. But when it is in AP mode and I turn on my home router, then the script remove the AP and connect to my home AP, but with DHCP IP address and not with my interfaces static IP address.

Is there a way to config everything to work as I want to?


Thank
Hi Leonardo

The reason you lose the hotspot when the router is turned on is because there are two network mangers running. The network manager which uses the interfaces file and separately dhcpcd. As mentioned in the guide the /etc/network/interfaces file needs to have no network configuration.

The interfaces file is depreciated in Raspbian and dhcpcd is the main network manager though im guessing its still used in Ubuntu.

wpa_supplicant would be enabled by the interfaces file, which will always over ride the hotspot.

I would suggest you clear out the network/interfaces file so only the top 3 lines are shown:
# interfaces(5) file used by ifup(8) and ifdown(8)
# Include files from /etc/network/interfaces.d:
#source-directory /etc/network/interfaces.d

The static ip config for when your connected to your router should be in dhcpcd.conf

The static iP details for the hotspot are in /etc/dnsmasq.conf and the /usr/bin/autohotspot script.
for this they should both be in the same ip range ie 10.0.0.# .the range in dnsmasq.conf is what connected devices get. The ip in the /usr/bin/autohotspot script is the hotspots ip.
Look for this section
createAdHocNetwork()
{
echo "Creating Hotspot"
ip link set dev "$wifidev" down
ip a add 10.0.0.5/24 brd + dev "$wifidev"
ip link set dev "$wifidev" up
dhcpcd -k "$wifidev" >/dev/null 2>&1
systemctl start dnsmasq
systemctl start hostapd
}
and change the hotspots ip address there if required.


The priorities in your wpa_supplicant file will be fine.
The script will go to network mode if it detects any of the ssids but on connection wpa_supplicant will pick the highest priority if it is available.

Hope this helps make the setup clearer.
Ok, I understand.
I can't find how to config static ip for each of my home routers in dhcpd. I've just found this:

interface wlan0
arping 192.168.2.1
arping 192.168.0.254

profile 192.168.2.1
static ip_address=192.168.2.44/24
static routers=192.168.2.1
static domain_name_servers=192.168.2.1

profile 192.168.0.254
static ip_address=192.168.0.44/24
static routers=192.168.0.254
static domain_name_servers=192.168.0.254

but, how do I link those "arping" with my routers?

Thank!
Hi Leonardo

You can find your routers ip address a few ways.
While connected to a router enter ip route | grep default
the ip shown is the Arping ip as well as the static routers ip.

You can also use a web browser and find a service that shows your router Private ip. http://whatsmyrouterip.com/

for the static ip make sure the first 3 digits are the same as your routers ip and just change the last digit.

I haven't use a static ip on my Pi's but have tried this setup and it has worked on a single router setup. I will have a go at a multiple router in the next day or so.


Hope this helps
Hello,
Thanks for this write up! It worked great setting up a RPi 4b.

I did run into one issue which I see other people have encountered as well. Namely being unable to connect via ssh to the hotspot. After spending a couple of hours troubleshooting and getting no where, I decided to disable the autohotspot and try the RaspAP solution.

After disabling the autohotspot service, I went to remove the nohook wpa_supplicant entry from /etc/dhcpcd.conf file and discovered it wasn't there.

Instead to removing it, I added it to the bottom of the file, re-enabled the autohotspot service and rebooted the Raspberry Pi.

After the reboot I was able to successfully connect via ssh from my Android tablet!

I'd completely missed the instructions to add nohook wpa_supplicant to the dhcpcd.conf file.

Thanks again!
Hi Chuck,

I'm glad you found the issue.
If the nohook wpa_supplicant line is not included then the Pi generates two ip addresses during the hotspot. This causes some devices to see the hotspot as unstable and get in a connection, un-connection loop. Which is why ssh or any other type of connection will fail.

Some devices are more tolerant and connect fine.
Hi,

First of all thanks for your work, it works perfectly.

My problem is one of the trouble shooting, this one specifically: You can connect to the hotspot via an Android Phone but you can't get a ssh connection

I need to be able to connect to the Rpi via SSH and have phone data at the same time, in my case I'm hitting an endpoint to get a command to later on be able to send it to the Rpi, so it's not possible to disable the data in my scenario.

What can I do then?

Thanks in advance.
Hi Fernando

unfortunately this is an Android issue using ssh with the hotspot or over the network and not anything to do with the Pi. You will need to disable data for the ssh app you are using so phone data can be left on. I use JuiceSSH and there is only an option to turn off background data which is no help. You probably would need to install a data manager like netguard to disable just the ssh app.

There may also be an option in your app's settings to only use wifi.
Do you think Wifi-direct will solve this issue?

If so, the Rpi can have the Wifi-Direct active while been connected to another wifi at the same time? or do I need an script doing the same thing you've done in your article?

Thanks,
Fernando
Hi Fernando

I haven't tried to setup Wifi Direct on a PI but the Hotspot is the same type of thing.
As far as i'm aware you can only connect one wifi connection from the PI to another device at a time. You need a usb wifi adaptor to make a second connection.

The issue just seems to be with android ssh. You don't need to turn data off if you use VNC from your phone to the PI. When the pi is in hotspot mode you can access a pi web server with data on as well. So i think it's just something about ssh on Android.
If your Pi program send an output through a webserver, service or protocol and you are able to capture that on a android app then it will work fine in hotspot or network mode. If you need ssh then it seems you need to be able to disable data for the ssh program.
Hi Fernando

Sorry the below is not correct. I had previously installed netguard on my phone and uninstalled it. was blocking ssh data still until I rebooted the phone.

(I may have found the fix.
if you change the Pi's ssh channel from 22 to something else it works without turning off Data.

In /etc/ssh/sshd_config
change #Port 22
to Port 2000
you can use any number over 1024.
Then on your android ssh change the connection port from 22 to 2000.
For me I connected without turning off data.)
Still not fixed changing the port you suggested, I've tested with my gf's phone (Android) and still the same issue...

I've opened a post in stackoverflow

https://stackoverflow.com/questions/60367385/ssh-to-hotspot-doesnt-work-when-mobile-data-on

to see if somebody can help too, looking at issues in android to see if somebody got the same problem, and I will try Wifi-Direct just in case.

I will keep updating this thread to see if I can help to fix this issue
I'm going to try this library as soon as I get home, I will keep you all updated.

https://stackoverflow.com/questions/55938253/react-native-force-fetch-to-use-wifi

https://github.com/devstepbcn/react-native-android-wifi#readme (at the bottom)
Just want to drop a big thank you. This is exactly what I was after, the tutorial is super well written and everything worked like a charm :).

Take care.
Thanks Ben,your welcome. I'm glad you have found it useful.
After the hotspot is up i can connect to it with my laptop and get an ip but i can not access the pi using ssh nor my webserver on the pi. Any firewall settings i am missing? Any logs i should look at?
Hi Petfrogg

This can happen if hostapd is enabled at boot rather than being activated by the script. you can tell if thats the case by checking the ip of the hotspot.
In Hotspot mode enter ip addr , if the wlan0 ip address is not 10.0.0.5 but starts with 169.254 then disable the service.
sudo systemctl disable hostapd, do the same for dnsmasq just to check.
Then reboot.

If you still have an issue check the ip range in /etc/dnsmasq.conf are for this Direct Hotspot script, starting with 10.0.0

let me know if this doesn't help and I will look into it further.
Hey, this is an amazing tutorial! Thanks for putting it together.

It didn't work for me on the first try because I had to add the interpreter to your .service file (#!/bin/bash)

Does this only happened to me?
I'm using a RPI Zero W running Booster.

Thanks again for this great tutorial!
Hi Angel, your welcome :)

I'm not sure why you would need #!/bin/bash on the service file, it's not been required in any service file I have used.
The autohotspot script requires it but not the autohotspot.service file.

What installation of Raspbian Buster are you using, Full, Lite, Noobs?
Are you using the default PI user or your own user?

As a test can you take #!/bin/bash back out of the autohotspot.service file. Then reboot.
then enter sudo systemctl status autohotspot

and let me know of any errors it reports.
Thanks
Hey Roboberry,
Here is what I get without the interpreter line:

Jan 31 19:50:07 evita systemd[1]: Starting Automatically generates an internet Hotspot when a valid ssid is not in range...
Jan 31 19:50:07 evita systemd[353]: autohotspot.service: Failed to execute command: Exec format error
Jan 31 19:50:07 evita systemd[353]: autohotspot.service: Failed at step EXEC spawning /usr/bin/autohotspot: Exec format error
Jan 31 19:50:08 evita systemd[1]: autohotspot.service: Main process exited, code=exited, status=203/EXEC
Jan 31 19:50:08 evita systemd[1]: autohotspot.service: Failed with result 'exit-code'.
Jan 31 19:50:08 evita systemd[1]: Failed to start Automatically generates an internet Hotspot when a valid ssid is not in range.

The way I'm solving this now is by adding the interpreter to the ExecStart command, leaving my autohotspot.service like this:

[Unit]
Description=Automatically generates an internet Hotspot when a valid ssid is not in range
After=multi-user.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash /usr/bin/autohotspot
#ExecStart=/usr/bin/autohotspot
[Install]
WantedBy=multi-user.target


I just noted how adding the interpreter at the beginning of the file (#!/bin/bash) does not solve the problem, but adding it on the ExecStart does.

I am using Raspbian Buster Lite with the default user, but I changed the hostname to evita.

Please let me know if there is any other debugging I can help you with here.
Hi Angel

thanks for the output.
I have reproduced your error message.
In the /usr/bin/autohotspot script either
#!/bin/bash is missing or it is not on the top line, you may have a blank line at the top of the file.

If that is the case, correct that and then you can take the bash entry out of the service file and try again.

Let me know if that resolves the issue.
Hey Roboberry,
Thanks for chasing this!
That's what I thought at fist, but it looks like everything is fine on that file. Here is a cat -A of the first few lines:

pi@evita:~ $ cat -A /usr/bin/autohotspot
#!/bin/bash$
#version 0.95-41-N/HS$
$
#You may share this script on the condition a reference to RaspberryConnect.com $
#must be included in copies or derivatives of this script. $
$
#A script to switch between a wifi network and a non internet routed Hotspot$
#Works at startup or with a seperate timer or manually without a reboot$
#Other setup required find out more at$
#http://www.raspberryconnect.com$
$


Anyway, it works with the line on the service file, so I don't think it's worth spending more time on it for now unless someone else has this issue.

I have one more question, but I will open a new thread for that.

Again, Thank you very much for this amazing tutorial!
Hi Angel

That's strange it's like it doesn't know it's a bash script. There is no special invisible character at the start to make the line invalid.

Out of interest did you copy the script from the webpage or from the download link?

at least you have a fix.
Hey!
I used the download link because I've already had similar issues in the past.
No idea what this could be about.

Thanks!
Hey Roboberry,
Question on a different topic.
I'd like to ssh on to the pi by it's hostname.
This works when it's connected to another WiFi, but not when it's serving as hotspot.

I've been reading a bit about dnsmasq, but I can't figure out why the behavior is different when operating as an AP and not.

Could you point me in the right direction to fix this?

Thanks!
Hi Angel.
you can add the hostname to the /ect/hosts file.
This is the file that your network hostname is in, which you will see at the bottom.

add the hotspot ip of 10.0.0.5 and the name you want.

this is my entry with Buster16 for both network and hotspot

127.0.1.1 buster16
10.0.0.5 buster16
Hey Roboberry, thanks for the suggestion.
I tried it, but it still doesn't resolve the address to it's own.

I have the following line in /etc/hosts
10.0.0.5 evita

and dnsmasq.conf is set as it is by default, so it should be expanding on /etc/hosts, but it's not because I cant ssh pi@evita still.

I'm curious... Is it working for you? can you ping buster16 from your computer?
Hi Angel
It works fine for me, I sign in to ssh with pi@buster16 to the hotspot.
Thought I'm running the internet version of this script from the other guide. There shouldn't be anything to stop it working in the this direct script.
I will switch scripts this evening and double check and let you know.
Interesting!
So just to make sure I understand your test, are you connected to the RPI via its own hotspot or is the RPI connected to a WiFi?
The Pi is in Hotspot mode which is connected to by an Android phone. Then use ssh@buster16 to connect instead of pi@192.168.50.5

But I will check the direct setup works in the same way.
Hi Angel

I have setup the direct Hotspot on a pi, put it in hotspot mode and manage to connect to it fine with my Android phone using ssh pi@hostname rather than ssh pi@ipaddress

I then tried from my Linux Desktop (usually connect via the router) but enabled wifi and tried ssh pi@hostname and it failed to resolve name. ssh pi@ipaddress worked fine.

So it seems my phone is far more forgiving than my PC.
This happens the same for the Net enabled Hotspot as well. Which has a different dnsmasq setup.

So that confirms what you're seeing. From what I can see dnsmasq uses the /etc/hosts file so it is expected to work.

I would like this working other than my phone so if I find the cause I will let you know.
That did it! I wondered why you'd posted the scripts as downloads when all I had to do was copy and paste....NOW I know why!

Thanks for the quick reply, I'll be using this for a demonstration this week.
Bob
Hi Bob

Glad you have it sorted. I often find it easier to copy from text files rather than webpages and it gives you the option just to download it as well. User pref :)

I would be interest to hear what your demonstrating and how the script is being used.
Thanks for what looks like a very useful script.

Unfortuantely it will not work for me. I'm having the same error reported by Mats which I do not see a response to:

Running the autohotspot script i get the following response:
/usr/bin/autohotspot: 21: /usr/bin/autohotspot: Syntax error: "(" unexpected

That corresponds to the line:
ssids=($wpassid)

I can't see anything wrong with that line that is causing an error, and have double-checked everything twice and followed all the suggestions in the Troubleshooting section. Thanks for any assistance!
Hi Robert

The error is probably due to a missing character or a line has been split across two line. Not always obvious to spot.

I would suggest that you download the file in the "Download" link above the script in this article.

remove .txt by renaming it to autohotspot and copy it to /usr/bin/
Then make it executable with sudo chmod +x /usr/bin/autohotspot
and try again.

If you still have issues, your welcome to email me your autohotspot file and I will take a look.
Thank you for this tutorial. I got it working on my first try without much prior experience with Raspberry. Thank you!
Hi Tommy, You're welcome.
I have only used the script on Raspbian so I can't say how it would run on other variants of Debian.
I have just had a look at some network info online about Kali and it seems it is setup like Raspbian was pre Jessie using the /network/interfaces route. The autohotspot script uses dhcpcd.config rather than /network/interfaces.

You say you installed wpa_supplicant, if Kali doesn't use wpa_supplicant for wifi by default, then whatever is the default wifi setup would need to be disabled to go to a hotspot as the network wifi overrides the hotspot wifi. which is probably where the conflict is.

The concept to do the switch is that dhcpcd is disabled for wifi and wpa_supplicant is shutdown. Then dhcp is given to dnsmasq and hostapd is brought up. To go back the whole lot is reversed.

I plan to do some updates and add new stuff in the new year. It may be worth having a look at Kali and other variants and see what can be converted.
Awesome project! Thanks for sharing it.
I am trying to make this work on a Pi 4 running Kali. It seems like there are conflicts when I install/run wpa_supplicant. Have you tried to do this on Kali? Thanks again!
Hi Mats

I would guess that a line has not coped completely or an entry has split across two lines causing the syntax error.

Easiest option would be to recopy it from the download link. Otherwise compare the script to the one online and see if you can spot what is different from the lines around the line you highlight.

If you recopy the download link over the top of the existing autohotspot file you will probably need to do chmod +x /usr/bin/autohotspot again.


let me know if you still have issues
My hotspot do not start.

Running the autohotspot script i get the following response:
/usr/bin/autohotspot: 21: /usr/bin/autohotspot: Syntax error: "(" unexpected

That corresponds to the line:
ssids=($wpassid)

What is wrong? I have only copied the script
Hi!
First thank you for this tutorial.
Unfortunately I could not make it work.

I created a GIST for the bash script I wrote based on your article.
File name is `install-auto-hotspot.sh`

https://gist.github.com/hekigan/3e79ba728065fd88b3d6a6a88eaf2942

My OS is Dietpi Stretch (Debian 9) on a rpi 3B+

What happens is, the hotspot shows up on the wifi (in MacOS) and I can connect to it, but I have no IP address given for the Mac, and when checking on the rpi, it does not have any ip address either...

`/etc/dhcpcd.conf` only contains `nohook wpa_supplicant`, nothing else.

/usr/bin/autohotspot is running (status was ok)

So I am a bit at a loss of what to do to make it work.
Hi Laurent

You beat me to the installer, was planning to do that in the new year :)

The setup has only been tested on Raspbian. So I can't guarantee it will work on other variants.

The issues will be around hostapd and dnsmasq.
If there is no ip then dnsmasq is the issue, it probably failed due to an error in the system or config.

run sudo systemctl status dnsmasq and see if there is an error.

Check that the ip in dnsmasq.conf is in the same range at the autohotspot scripts ip. So for the direct script it should be 10.0.0.5 for autohotspot and 10.0.0.50 - 10.0.0.1.50 in dnsmasq.conf

If DietPi dosn't use wlan0 for wifi network it needs to be changed in hostapd.conf, dnsmasqq.conf and /usr/bin/autohotspot 9th line

Check that hostapd hasn't been remasked or enabled after an update. Though Stretch is probably still using the older version that wasn't masked by default.

Do you get any ip for wifi?

let me know how you get on and I will look into it further.
Quoting Roboberry:
Hi Laurent

You beat me to the installer, was planning to do that in the new year :)

I would love to help test, as I would really like to have a working script. I'll Try Laurnet's in a few days and se if I can get some useful feedback
Hi Scott

I would be happy to try and get to the bottom of your issue. Looking at our last comments, if you can give me some further info I will try and debug your issue

Can you let me know:

Could you give me some details of your setup please as you have it setup on wlan1.

Which Pi are you using?

If you have internal wifi and usb wifi, sometimes they swap wlan port. ie internal wlan1, usb wlan0.

Which usb wifi device are you using?
Incase it is not hotspot compatible. Some wifi chips need a different version of hostapd so won't work with Raspberry Pi wifi drivers.

Can you just confirm that the references to wlan0 in hostapd.conf, dnsmasq.conf and usr/bin/autohotspot (line 9) have all been changed to wlan1.

If you run the hotspot manually what message do you get; sudo /usr/bin/autohotspot

While it is in the failed hotspot mode, does hostapd say it is running?
sudo systemctl status hostapd

any errors in dnsmasq?
sudo systemctl status dnsmasq

Any further info of what happens would be useful.

you can e-mail me at admin@ this site to make it a bit easier if you want.
Sorry, "working installer script" ;)

I have got the hotspot working, it just sometimes has a weird delay I can't account for.
Hi Scott

It's most likely be due to another process starting slowly.

You can have the hotspot start earlier in the bootup sequence, but it may cause it to go to a hotspot when the network is available. Though if you set a cron timer for 2 minutes it will switch back to wifi soon after.

In the /etc/systemctl/system/autohotspot.service
change
After=multi-user.target
to
After=network.target

and reboot. Any issues just change t back.
Hi, thank you for your reply.

The ip address and range were both fine.
And wlan0 was used but did not have any IP.

I think that I had 2 issues:
- Dietpi is acting weird when installing other softwares (through their own system). And because of that, it would fail quickly even after a fresh install. This is unrelated to the hotspot problem, but made me move back to Raspbian.
- with stretch, dnsmasq ~2.76 is the default and can not be upgraded from what I saw without having to compile the other dependencies. It's annoying and don't want to deal with that for each install that I do.

So I installed a fresh Raspbian Buster image, put Raspap software (which failed before), and now everything is working like a charm.

In conclusion, dnsmasq was the main culprit I believe, and most scripts would fail because of that.
So the solution is a Raspbian Buster install, and I am guessing -not tested- that my installer would work now. I have not time for it now, so until I do Raspap it is.

Thank you again for your great tutorial
Hi Laurent

It may just be a different setup on DietPi. People have tried other variants on Jessie and had issue. I have not had any requests from any other Buster variants yet. Though dnsmasq was an older version on Stretch it did work, at least with my setups, though that doesn't mean a recent Stretch update hasn't caused issues. I will have to update a Stretch copy and see what happens.

I'm glad you have a solution that works for you and thanks for your feed back.
I have set up my Pi 3 as a hotstpot and this part works fine. However, I want the pi work also as an UDP server/client, but UDP traffic is for some reason blocked; no packet going to/from the server. If pi is not as a hotspot then the UDP works fine. What could be the reason for this behavior?
Hi Eero

UDP will work in hotspot mode but there may be a timing issue. If upd starts before the hotspot is ready it may use a ip address from dhcpcd. But when the autohotspot starts it shuts down dhcpcd for wifi and craetes an ip for wifi on dnsmasq. UPD would not be on the right setup. If UPD starts after the ip it ready it should be fine. If the autohotspot switches back to network at some point, either manually or via timer the ip will change again and the upd connection will probably be lost again.
Thanks for your answer. Do you know if there is a way to restart udp services after hotspot starts? Then it would always get the right ip.
I'm about setting up an headless RaspberryPi ZeroW for the lan of my computer-not-so-literate father.

With you script and the ability to automatically start a "known" Hotspot may his router was down is great. I'm covering my ass!

Just checking your script trying to understand what it does (I'm not very code fluent…) :

"
elif echo "$ssidreply" | grep "Network is down (-100)" >/dev/null 2>&1 ; then
echo "Network Not available, trying again" $j
j=$((j + 1))
sleep 2
elif echo "$ssidreplay" | grep "Read-only file system (-30)" >/dev/null 2>&1 ; then
echo "Temporary Read only file system, trying again"
j=$((j + 1))
sleep 2
"
Is "$ssidreplay" correct? Shouldn't it be "$ssidreply" like the other occurrence?


For now I'm trying to make your script work with pi-hole (which somewhat fiddle with dnsmasq and replace it with it's own system).
Hi Renaud, your right it's a typo it should be $ssidreply. thanks for letting me know, I have read that script sooooo many times :)

Unfortunately I don't know what setup is required with PiHole but if you have to change the dhcp range in dnsmasq make sure the autohotspot script has the same ip for the first 3 numbers.

Let me know if you need further info
As such your script doesn't work with Pi-Hole installed. But I guess I knew it before installing.
The Pi-Hole installation alters the dnsmasq configuration somewhat. Pi-hole now uses a Pi-hole flavored version of dnsmasq called "FTLdns" / "Pi-Hole FTL".

The problem is their DHCP server partially uses the assets (configuration files) of dnsmasq and/or alters dnsmasq configuration so that it doesn't interferes with Pi-Hole.

The Hotspot (hostapd) seems to appear and work but the DHCP server (dnsmasq) doesn't. Any machine which connects to the Hotspot isn't given any IP.
But the RaspPi correctly changes its IP address to 10.0.0.5 so I can nonetheless access to it via ssh (> I manually changed my mac IP/mask/router).
The services installed on the Box doesn't work (shairport-sync / netatalk)

I'm a somewhat newbie in code, but I search for a solution :
- maybe use FTLdns instead of dnsmasq? (beyond my skills)
- alters dnsmasq configuration?
- alters the autohotspot script to turn off momentarily pi-hole then change dnsmasq configuration…
Hi Renaud
Thanks for the update. I would need to see what pi hole does. The script won't care what software is doing the dns it would just need to be in the same ip range. In theory finding out what ip range pihole is using and change the ip in autohotspot from 10.0.0.5 to piholes ip ???.???.??.5 there may be more to it. If i get time i will see what config needs changing. It would be interesting to see.
I think I'm in the way of a workaround. That's nice : trying to make Pi-Hole and Autohotspot works together is my makeshift "Bash Scripts and Raspbian Network Configuration 101"!

Pi-Hole is using whatever IP address range my router is using. The problem is that my router is rather finicky and poorly designed (hardcoded "public" IP address used for internal use > impossible to use Cloudflare in the Lan; impossible to change the routers DNS resolver due to dubious reasons…).

That are the reason why I need to use Pi-Hole's own DHCP and DNS resolver.

I like the idea to have a distinguish IP range between "main branch" (Pi-Hole&Router) and "SOS branch" (Autohotspot).

It's not perfect, but trial and errors made me :
> edit dhcpcd.conf to have multiple profiles (and a "fallback" one dedicated to Autohotspot — I don't know if that one is actually useful nor effective.

> edit somewhat autohotspot.sh to :
- turn off/on Pi-Hole DHCP and resolver before the Hotspot is started or stopped
- switch automatically dnsmasq configuration between Pihole's and Autohotspot when The hotspot is started and stopped

> make a few scripts and crontab edits to :
- make sure that the "good" dnsmasq configuration is in place when the Pi starts (in case of power outage when the wifi is on Hotspot mode > the files and folders may be wrong)
- save the pi-hole's dnsmasq configuration somewhere every now and again (to avoid a "old" configuration be written over a "new" one at startup.:


What work :
- hotspot starts and stop nicely when needed
- it was hard but PiHole successfully restart somewhat (dns resolution / ad blocking).

What doesn't work :
- Pi-Hole's DHCP doesn't restart / is unreliable. I need to reboot the Pi to make it work properly.
Hi Renaud

It's good to hear you have it working and it's possible to configure them both together.

The fall back you mention on dhcpcd for autohotspot won't be used in hotspot mode as the script disables dhcpcd on wlan0. So you probably don't need that.

When your happy with it I would be interested to take a look at your update. It will probably be useful to others.

Roboberry
further to last comment
yes you can do sudo crontab -e but
you need to set the path variable in the crontab

this is what I have
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/5 * * * * /usr/bin/autohotspotN >/dev/null 2>&1
Hi Daniel

Thank you, glad you found it useful.
When the Pi goes from Hotspot to Wifi it just reinstates wifi in the same way wifi is started when you first bootup on a pi without the autohotspot. So it "should" act the same way. I take it you have been getting login pages until you used the autohotspot?

I had a quick look online and it is possibly and issue if when a dns server such as goggle on 8.8.8.8 is set the page doesn't load because the wifi providers dns is not used. Google is set for the other autohotspot script for internet but not this Direct article.

So it may just be a setting but I would have to take it somewhere and try.

Have you previously used the same wifi provider which then stopped when the autohotspot direct script was setup? Any other info would be helpful. thanks
Great tutorial, thank you. I do have a follow up question:
Auto connecting to a known wifi doesn't seem to work if the wifi requires an acceptance of terms and conditions after connecting.
Would it be possible to call a POST request when connecting to a wifi like that? The POST would be the link that the browser would call when the HTML form is posted. (This would be different for each wifi)
Hi Scott

Could you give me some details of your setup please as you have it setup on wlan1.
Can you just confirm that the references to wlan0 in hostapd.conf, dnsmasq.conf and usr/bin/autohotspot have all been changed to wlan1.

If you run the hotspot manually what message do you get; sudo /usr/bin/autohotspot

While it is in the failed hotspot mode does hostapd say it is running?
sudo systemctl status hostapd


The purge dns-root-data should be done first as a precaution for Jessie and stretch but I have never had an issue with it on any of my pi's but it has solved some users issues so it may just be specific to some setup with other software installed.

The masked hosapd service seems to have started when Buster was released but the autohotspot scripts start hostapd themselves so the service is not used, so shouldn't be an issue. It's noted on the static hotspot which it would be an issue for. but thanks for highlighting you experienced it as well.

Let me know how you get on and I will try to solve your issue.
apparently it just takes some amount of time (in multiple minutes) before the hotspot is broadcast. This is after I unmasked hosted, so I am not sure if that is required or not, I would have to rebuild from scratch and not unmask and see if it ever appears. Should it take several minutes to begin broadcasting?
Hi Scott, no it shouldn't take several minutes to go to the hotspot. Try changing the channel in hostapd.conf to something else between 1and 12. There are various conditions to cause it to retry but that shouldn't take more than 10 seconds. If you run it manually you can see what it does as it tries to create the hotspot. Sudo /usr/bin/autohotspot
If you have other software running at startup that is slow, it can cause a delay before the script is run. If it switches during use of the pi then it should be quick.
Hi Scott

You can use system-analyze to see if you have other software that is starting slow.
to see total startup time of Raspbian; sudo systemd-analyze

For each stage of start up; sudo systemd-analyze time
and longest to shortest service: sudo systemd-analyze blame

maybe this will highlight which service is causing a long delay.
The static hotspot shouldn't cause a delay.
The Autohotspot scripts do an additional check after 20 seconds so they will say they take around 21 seconds.
I am unable to get this working as I have done in the. Using an install of Stretch, updated to latest. Upon testing, ifconfig shows wlan1 to be using the correct IP address, but no hotspot is being broadcast. I have unmasked Hospapd (that should be added to your instructions and tried to purge dns-root-data (it is unclear where in the steps that should be done) all to no avail.